I have an asyncTask to get the profile of a user. I want to run this task and get the data from the JSON object. Data as in user's emailId, password, location, mobile no etc. I want to show this in edit text when the fragment will get start.
getProfileAsyncTask
public class GetProfileAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
private Context context;
public GetProfileAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/user/getprofile.php";
jsonParams = new JSONObject();
String username = params[0]; // params[0] is username
jsonParams.put("user", username);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 0 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
I tried to access the data from JSON object but it is throwing JSON exception and null value for userUsername.
Fragment :
public class BasicInformationFragment extends android.support.v4.app.Fragment {
EditText email,pass,mobile,code;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
JSONObject jsonParams;
String userId,password,mobileNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_basic_information,
container, false);
try {
GetProfileAsyncTask task = new GetProfileAsyncTask(getActivity());
JSONObject obj = new JSONObject();
userId = obj.getString("userUsername");
task.execute(userId);
password = obj.getString("userPassword");
mobileNumber = obj.getString("userMobileNo");
email = (EditText) view.findViewById(R.id.edt_email);
pass = (EditText) view.findViewById(R.id.edt_pass);
mobile = (EditText) view.findViewById(R.id.edt_mobile);
code = (EditText) view.findViewById(R.id.edt_code);
email.setText(userId);
pass.setText(password);
mobile.setText(mobileNumber);
}
catch (JSONException e)
{}
return view;
}
}
user parameters:
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
How to do this?
Related
I am developing an Application of JSON object Which Returns data into ListView.
if json have data then show data in listview..if dont have date then application is crashes.my application is crashes when json is empty.how to resolve this problem..thanx in advancce
here is android code..
public class EmployeePaymentHistory extends Fragment {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
ListView CategoryListView;
ProgressBar progressBar;
List<String> IdList = new ArrayList<>();
private String TAG = EmployeePaymentHistory.class.getSimpleName();
// Http Url For Filter Student Data from Id Sent from previous activity.
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
String TempItem;
ProgressDialog progressDialog2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_employee_payment, container, false);
CategoryListView = (ListView)view.findViewById(R.id.listview1);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getActivity().getIntent().getExtras().getString("ListViewValue1");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
// Add Click listener on Delete button.
return view;
}
// Method to Delete Student Record
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new EmployeePaymentHistory.GetHttpResponse(getActivity()).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("CustomerID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, api.EmployeePayment);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
List<Customer> CategoryList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Customer category;
CategoryList = new ArrayList<Customer>();
for(int i=0; i<jsonArray.length(); i++)
{
category = new Customer();
jsonObject = jsonArray.getJSONObject(i);
category.CustomerName = jsonObject.getString("date").toString();
category.Customertotal = jsonObject.getString("account").toString();
category.CustomerPaid = jsonObject.getString("total").toString();
category.CustomerUnPaid = jsonObject.getString("status").toString();
CategoryList.add(category);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "abcc", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
CategoryListView.setVisibility(View.VISIBLE);
CustomerListAdapterClass adapter = new CustomerListAdapterClass(CategoryList, context);
CategoryListView.setAdapter(adapter);
}
}
}
here is php Api code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$CustomerID= $_POST['CustomerID'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "sELECT b.payerid,a.account as account,b.date as date,b.status as status,b.type as type,sum(b.amount) as total FROM crm_employees a left JOIN sys_transactions b ON a.id = b.payerid where payerid= '$CustomerID' group by b.date ORDER BY a.id desc" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
You need to give the response output same as you are parsing in android side. If you are trying to find a Json object of key name which is not in response then it will crash.
In this scenario you need to handle manually, the values you think it will be null or empty then handle using normal if statements.
Suppose jsonObject.getString("date") object is not fount then using if statements you can handle.
if(jsonObject.getString("date") != null){
//code here
}
I have written a program to post some json data and get the same json data so that i can show the data in a ListView in the same activity.
Posting the data and getting the data is done with the help of volley library.
So my problem is when I type something inside my EditText and click on the button to post some data , the data gets posted but I am not able to view it instantly inside my ListView , in short data is not getting refreshed instantly inside my ListView.I have also tried using notifyDataSetChanged() but all in vain.
I am posting my whole activity here , please tell me where exactly i have to set my adapter , my ArrayList and the notifyDataSetChanged()
public class Write_Answers extends ListActivity{
Boolean isInternetPresent = false;
ConnectionDetector cd;
TextView txtQuestions;
String questions;
EditText editAnswers;
Button btnAnswer;
String postAnswerUrl = "";
String getAnswerUrl = "";
public String answers;
SessionManager session;
String userType,deviceId,questionId;
ListView lvAnswers;
public static final String TAG_QUESTION_ID = "QId";
public static final String TAG_TRANSACTION_ID = "TransactionId";
public static final String TAG_ANSWERS = "Answer";
public static final String TAG_DATE= "Date";
public static final String TAG_TIME = "Time";
public static final String TAG_DEVICE_ID = "DeviceId";
public static final String TAG_USER_TYPE = "UserType";
ArrayList<HashMap<String, String>> answersList;
CustomAnswerAdapter customAnswerAdapter;
HashMap<String,String> ans_details_map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.write_answers);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
txtQuestions = (TextView) findViewById(R.id.textQuestions);
editAnswers = (EditText) findViewById(R.id.edtAnswer);
btnAnswer = (Button) findViewById(R.id.btnAnswer);
questions = getIntent().getStringExtra("questions");
txtQuestions.setText(questions);
answersList = new ArrayList<HashMap<String, String>>();
customAnswerAdapter = new
CustomAnswerAdapter(Write_Answers.this,answersList);
lvAnswers = getListView();
lvAnswers.setAdapter(customAnswerAdapter);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
questionId = getIntent().getStringExtra("questionsId");
postAnswerUrl = "http://gps.traxistar.net/PostAnswers.svc/PostAnswers";
getAnswerUrl = "http://gps.traxistar.net/GetAnswers.svc/GetAnswers;
////////////////////////// get the data from the server the ones which i have to set to the adapter and show in the Listview ///////////////////////
if (isInternetPresent) {
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(getAnswerUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Json Array", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject json = response.getJSONObject(i);
String ques_id =
json.getString(TAG_QUESTION_ID);
String trans_id =
json.getString(TAG_TRANSACTION_ID);
String device_id =
json.getString(TAG_DEVICE_ID);
String ans = json.getString(TAG_ANSWERS);
String answerDate =
json.getString(TAG_DATE);
String answerTime =
json.getString(TAG_TIME);
String userType =
json.getString(TAG_USER_TYPE);
ans_details_map = new HashMap<String,
String>();
ans_details_map.put(TAG_ANSWERS, ans);
ans_details_map.put(TAG_DATE, answerDate);
ans_details_map.put(TAG_TIME, answerTime);
answersList.add(ans_details_map);
}
} catch (Exception e) {
e.printStackTrace();
}
customAnswerAdapter.notifyDataSetChanged();
lvAnswers.setSelection(answersList.size() - 1);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley Error", "Error: " + error.getMessage());
Log.d("Error", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
} else {
showAlertDialog(getApplicationContext(), "No Internet Connection",
"You don't have internet connection.",
false);
}
btnAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answers = editAnswers.getText().toString();
if (answers.equals("")) {
Toast.makeText(getBaseContext(), "Please write an answer",
Toast.LENGTH_LONG).show();
} else {
if (isInternetPresent) {
postAnswers();
editAnswers.setText("");
} else {
showAlertDialog(getApplicationContext(), "No Internet
Connection", "You don't have internet connection.",
false);
}
}
}
});
}
////////////////////////////// posting the data to the server on button click ////////////////////////////
private void postAnswers() {
Calendar in = Calendar.getInstance();
Date dt1 = new Date();
in.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
SimpleDateFormat sdf1 = new SimpleDateFormat("E, MMM d, yyyy");
String dateval = sdf1.format(dt1);
SimpleDateFormat stf1 = new SimpleDateFormat("h:mm a");
String timeval = stf1.format(dt1);
final String date1 = dateval.toString();
final String time1 = timeval.toString();
final String datetime = dateval.toString() + "T"
+ timeval.toString();
final String transId = deviceId + "" + datetime;
answers = editAnswers.getText().toString();
List<Map<String, String>> listMap =
new ArrayList<Map<String, String>>();
Map<String, String> answersMap = new HashMap<String, String>();
answersMap.put("TransactionId", transId);
answersMap.put("DeviceId", deviceId);
answersMap.put("Answer", answers);
answersMap.put("QId", questionId);
answersMap.put("Date", date1);
answersMap.put("Time", time1);
answersMap.put("UserType", userType);
listMap.add(answersMap);
JsonObjectRequest jsObjRequest = new
JsonObjectRequest(Request.Method.POST, postAnswerUrl,
String.valueOf(new JSONArray(listMap)), new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Write_Answers.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Answer
posted", Toast.LENGTH_LONG).show();
}
});
Log.d("Json Response ",response.toString());
}catch(Exception e){
//Log.d("JSON Array", response.toString());
e.printStackTrace();
}
//editAnswers.setText("");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley Error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-type", "application/json; charset=utf-8");
return headers;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse
response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
if (response.data == null || response.data.length == 0) {
return Response.success(new JSONObject(),
HttpHeaderParser.parseCacheHeaders(response));
} else {
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
}
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
An ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
I recommend using the the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Any type of update (remove/edit/add) you want to do
(on Post Button click do your posting after that these steps)
1. update your ArrayList first
2. remove all views from ListView with previous ArrayList data
3. call the adapter again with the updated ArrayList again
hope this helps you.
Try calling notifyDatasetChanged() like this:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
customAnswerAdapter.notifyDataSetChanged();
}
}, 3000);
and check whether this is working
In this i want to cancel the asynctask i called aysnc task in listview onclickitem...
so if there is no data in particular row's then it will stop execution and remain on same activity.
I called the class in click and if condition if false as file_path is null then it will remain on same activity will not proceed further in another activity.
but in my case it will move to another activity i tried lot many things on this like oncancelled(), cancel(), etc methods but they are not working i put all in loop as well as switch case to break.
public class EAdFragment extends Fragment {
ListView lvAdSurvey;
JSONObject json = null;
public static final String FIRST_COLUMN = "Upl_ID";
public static final String SECOND_COLUMN = "File_Description";
JSONArray jarray = null;
JSONObject jsonObj = null;
String upload_type;
String upl_id;
File f;
String imgurl;
ProgressDialog pDialog;
String upl_ID, type_of_upload, file_description, amount;
String file_path = null;
String file_type, related_to, country, state, city, Number_of_user,
type_illegal;
GetData task;
ViewHolder holder;
public ListAdapter adapter;
String text;
public List<EAdvertActivityData> listData = new ArrayList<EAdvertActivityData>();
public void onViewCreated(View view, Bundle savedInstanceState) {
lvAdSurvey = (ListView) view.findViewById(R.id.lvAdSurvey);
new GetList().execute();
lvAdSurvey.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// String text =
// lvAdSurvey.getItemAtPosition(position).toString();
holder = (ViewHolder) view.getTag();
text = holder.txtFirstColumn.getText().toString();
Log.d("text:", text);
task = new GetData();
task.execute();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ead, container,
false);
return rootView;
}
private class GetList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected JSONObject doInBackground(String... args) {
String url = "url";
JSONParser jParser = new JSONParser();
jsonObj = jParser.getJSONFromUrl(url);
try {
jarray = jsonObj.getJSONArray("result");
Log.d("lengtharray:", String.valueOf(jarray.length()));
for (int i = 0; i < jarray.length(); i++) {
EAdvertActivityData data = new EAdvertActivityData();
JSONObject jobject = new JSONObject(jarray.get(i)
.toString());
upload_type = jobject.optString("Upl_ID").toString();
String description = jobject.optString("File_description")
.toString();
/*
* Log.d("upload_type",upload_type);
* Log.d("description",description);
*/data.setUpl_ID(upload_type);
data.setFile_description(description);
listData.add(data);
Log.d("data:", listData.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObject) {
EAdListViewAdapter adapter = new EAdListViewAdapter(getActivity(),
listData);
lvAdSurvey.setAdapter(adapter);
}
}
private class GetData extends AsyncTask<String, String, String> {
int flag=0;
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
SharedPreferences pref = getActivity().getSharedPreferences(
"SoundSettings", Context.MODE_PRIVATE);
String user_id = pref.getString("user_id", LoginActivity.userid);
String url = "url"
+ text;
JSONParser jParser = new JSONParser();
try {
json = jParser.getJSONFromUrl(url);
Log.d("jsonadvert:", json.toString());
String status = json.getString("fetchdata");
if (status.equals("Success")) {
type_of_upload = json.getString("Type_of_Upload");
file_description = json.getString("File_description");
amount = json.getString("Amount");
file_path = json.getString("file_path");
file_type = json.getString("File_type");
related_to = json.getString("Related_to");
country = json.getString("Country");
// state = json.getString("state");
Number_of_user = json.getString("Number_of_usr");
type_illegal = json.getString("Type_llegal");
Log.d("type_illegal:", type_illegal);
Log.d("file_path:", file_path);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
pDialog.dismiss();
if(file_path==null){
Toast.makeText(getActivity(), "Image does not exists", Toast.LENGTH_LONG).show();
pDialog.cancel();
task.cancel(true);
}else{
imgurl = "http://sharpersofttech.com/sign_up/" + file_path;
Intent in = new Intent(getActivity(), AdvertActivity.class);
in.putExtra("upl_id", text);
in.putExtra("file_description", file_description);
in.putExtra("imgurl", imgurl);
startActivity(in);
((Activity) getActivity()).overridePendingTransition(0, 0);
}
}
}
}
I am trying to do a update profile where I get my values from the EditProfile.java and displaying it on another page called ConfirmEdit.java to update the login record in database when user press the confirm button. I used intent putExtra to pass values from one class to another but have not been able to do so here.
As my code, I passed three parameters namely, username, name and handphone. But, when i did a print at ConfirmEdit.java, only username was printed out.
Kindly help thanks!
The codes are below:
EditProfile.java
public class EditProfile extends Activity {
Button backbtn, updatebtn;
String user, name_entered, username_returned, registered_name;
String handphone_no;
String updated_username;
EditText username, password_entered, name, handphone;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = url;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editprofile);
Bundle extras = getIntent().getExtras();
if (extras != null) {
user = extras.getString("username");
}
username = (EditText) findViewById(R.id.username_signup);
password_entered = (EditText) findViewById(R.id.password);
name = (EditText) findViewById(R.id.name);
handphone = (EditText) findViewById(R.id.handphone);
backbtn = (Button) findViewById(R.id.back);
updatebtn = (Button) findViewById(R.id.updatebtn);
new AttemptLogin().execute(user);
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
registered_name = name.getText().toString();
Intent i = new Intent(EditProfile.this, ConfirmEdit.class);
i.putExtra("registered_name", registered_name);
i.putExtra("user", user);
i.putExtra("password", password_entered.getText().toString());
i.putExtra("handphone", handphone.getText().toString());
startActivity(i);
}
});
/*updated_username = name.getText().toString();
new updateProfile().execute(updated_username, user, handphone.getText().toString() ,password_entered.getText().toString());
}
});*/
backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(EditProfile.this, AccountPage.class);
startActivity(i);
}
});
}
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("user", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(EditProfile.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
username_returned = json.getString("username");
handphone_no = json.getString("handphone");
name_entered = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
String messageString = username_returned;
username.setText(messageString);
String messageString2 = handphone_no;
handphone.setText(messageString2);
String messageString3 = name_entered;
name.setText(messageString3);
}
}
}
}
ConfirmEdit.java
public class ConfirmEdit extends Activity {
String name, handphone, username, password;
JSONParser jsonParser = new JSONParser();
private static final String UPDATE_PROFILE = url;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.confirmedit);
Button updatebtn = (Button) findViewById(R.id.cfmupdatebtn);
TextView t = (TextView) findViewById(R.id.textView10);
TextView t1 = (TextView) findViewById(R.id.textView11);
TextView t2 = (TextView) findViewById(R.id.textView12);
Bundle extras = getIntent().getExtras();
if (extras != null) {
name = extras.getString("registered_name");
username = extras.getString("user");
password = extras.getString("password");
handphone = extras.getString("handphone");
}
String messageString = name;
t.setText(messageString);
String messageString1 = username;
t1.setText(messageString1);
String messageString2 = handphone;
t2.setText(messageString2);
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new updateProfile().execute(name,username,handphone);
System.out.println(name);
System.out.println(username);
System.out.println(handphone);
}
});
}
class updateProfile extends AsyncTask<String, String, JSONObject> {
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("name", args[0]);
params.put("username", args[1]);
params.put("handphone", args[2]);
JSONObject json = jsonParser.makeHttpRequest(
UPDATE_PROFILE, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (json != null) {
Toast.makeText(ConfirmEdit.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
if (success == 1) {
Log.d("Acknowledgement!", message);
}
}
}
}
}
Ok, having:
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("user", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(EditProfile.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
username_returned = json.getString("username");
handphone_no = json.getString("handphone");
name_entered = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
String messageString = username_returned;
username.setText(messageString);
String messageString2 = handphone_no;
handphone.setText(messageString2);
String messageString3 = name_entered;
name.setText(messageString3);
}
}
}
you could add some custom and own constructor, as this:
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
String username, password, handphone, name;
public AttemptLogin(String _username, String _password, String _handphone, String _name){
this.username = _username;
this.password = _password;
this.handphone = _handphone;
this.name = _name;
}
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("user", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(EditProfile.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
username_returned = json.getString("username");
handphone_no = json.getString("handphone");
name_entered = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
String messageString = username_returned;
username.setText(messageString);
String messageString2 = handphone_no;
handphone.setText(messageString2);
String messageString3 = name_entered;
name.setText(messageString3);
}
}
}
So then you should change this line:
new AttemptLogin().execute(user);
to this:
new AttemptLogin(username, password, handphone, name).execute();
and that is a best way to handle that.
Hope that helps. Regards
EDIT
If you want to send your TextView/EditText or some control, you just have to change your constructor, as this:
EditText username, password, handphone, name;
public AttemptLogin(EditText _username, EditText _password, EditText _handphone, EditText _name){
this.username = _username;
this.password = _password;
this.handphone = _handphone;
this.name = _name;
}
And obviously when you process your data, you have to extract the string of that, so i think is the same thing. To get the String of an EditText/TextView is:
yourEditText.getText().toString();
I want to put AsyncTask instead thread in this simple code of SAX RSS parser
in ListFragment , and what is better Asynctask or multi thread.
this is my code
public class ListItem extends ListFragment {
public ArrayList<NewsItem> getValues() {
return values;
}
public void setValues(ArrayList<NewsItem> values) {
this.values = values;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_news_layout, container, false);
return view;
}
enter code here
public void onStart() {
super.onStart();
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
refresh();
listAdapter = new ListAdapter(getActivity(), R.layout.listitem,
getValues());
setListAdapter(listAdapter);
}
enter code here
public void refresh() {
Thread th = new Thread(new Runnable() {
public void run() {
ListHandler listHandler = new ListHandler();
try {
listHandler.processFeed();
setValues(listHandler.getNewsItemList());
listAdapter.setNewsItemList(getValues());
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
Actually Asynctask is also using thread but it is better for onpostexecute and onprexecute()
method callback if you use thread you dont get this by default .
Like this
private class HttpAsyncDealsTask extends
AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {
protected ArrayList<HashMap<String, String>> doInBackground(
String... dealslist) {
ArrayList<HashMap<String, String>> chekinRsp = new ArrayList<HashMap<String, String>>();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// mem_id
String mem_id = user.get(SessionManager.KEY_ID);
String rest_id = getArguments().getString("getid");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("rest_id", rest_id));
nameValuePairs.add(new BasicNameValuePair("mem_id", mem_id));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, ServiceHandler.POST,
nameValuePairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jresponse = new JSONObject(jsonStr);
JSONObject msg = jresponse.getJSONObject(KEY_MSG);
//String error = jresponse.getString(KEY_ERROR);
String msgss = msg.getString(KEY_MSGSS);
String error = msg.getString(KEY_ERROR);
if(error.equalsIgnoreCase("0"))
{
String getid = getArguments().getString("getid");
String getname = getArguments().getString("getname");
String getpoints = getArguments().getString("getpoints");
String getcomp = getArguments().getString("getcomp");
String getmemberpoint = getArguments().getString("getmemberpoint");
System.out.println(getid + getname + getpoints + getcomp + getmemberpoint);
CheckinPref checkin = new CheckinPref(getActivity());
checkin.Prefernce_save(getid
,getname, getpoints
,getcomp, getmemberpoint);
}
map.put(KEY_MSGSS, msgss);
chekinRsp.add(map);
// Log.d("OUT", msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.d("Response", e.getLocalizedMessage());
}
return chekinRsp; // return result
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> chekinRsp) {
System.out.println(chekinRsp.get(0).get(KEY_MSGSS));
TextView chekinResp = (TextView) getActivity().findViewById(
R.id.chekinResp);
chekinResp.setText(chekinRsp.get(0).get(KEY_MSGSS));
Button backButton = (Button) getActivity().findViewById(
R.id.btn_restback);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
fm.popBackStack();
}
});
}
}
and start this using
new HttpAsyncDealsTask().execute();