I have an activity that suppose to use JSON twice. In the first time it works perfectly, but on the second time it seems that the JSON class goes directly to the onPostExecute function without activating the doInBackground function. This is the activity that calls the JSON:
public class Registration extends ActionBarActivity {
public void regis(View view) {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass1 = (EditText) findViewById(R.id.PassTxt);
EditText pass2 = (EditText) findViewById(R.id.RePassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
CheckBox agree = (CheckBox) findViewById(R.id.checkAgree);
TextView err = (TextView) findViewById(R.id.err);
String uName = userName.getText().toString(), pss1 = pass1.getText().toString(),
pss2 = pass2.getText().toString(), disName = displayName.getText().toString(),
eMail = mail.getText().toString();
if ((uName.length() > 0) && (pss1.length() > 0) && (pss2.length() > 0) && (disName.length() > 0)
&& (eMail.length() > 0)) {
if (pss1.equals(pss2)) {
if (agree.isChecked()) {
err.setVisibility(TextView.INVISIBLE);
String str = "?uname=" + uName;
new JSONClass(this, 2, str, this).execute();
} else {
err.setText("You must approve the use terms");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("The two passwords must match!");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("You must insert values in every cell");
err.setVisibility(TextView.VISIBLE);
}
}
public void checkExist(JSONArray ans) {
try {
int cnt = Integer.parseInt(ans.getJSONObject(0).getString("cnt"));
if (cnt == 1) {
TextView err = (TextView) findViewById(R.id.err);
err.setText("User name already exists!");
err.setVisibility(TextView.VISIBLE);
} else {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass = (EditText) findViewById(R.id.PassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
String uName = userName.getText().toString(), pss = pass.getText().toString(),
disName = displayName.getText().toString(), eMail = mail.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
String str = "?uname=" + uName + "&password=" + pss + "&email=" + eMail + "&disnam=" +
disName + "&dt=" + currentDateandTime;
Log.e("log_tag", "Just for me: " + str);
new JSONClass(this, 3, str, this).execute();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void openLogin() {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
}
I removed unnecessary functions. This is my JSON class:
public class JSONClass extends AsyncTask<String,Void,JSONArray>{
private String link;
private int flag;
private Login log = null;
private Registration reg = null;
private Context context;
public JSONClass(Context context, int queryNo, String params, Registration regg) {
this.context = context;
link = "http://pickupfriend.fulba.com/android_project/query" + queryNo + ".php" + params;
reg = regg;
flag = queryNo;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected JSONArray doInBackground(String... arg0) {
JSONArray arr = new JSONArray();
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
arr = new JSONArray(result);
}catch(Exception e){
}
return arr;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void onPostExecute(JSONArray result) {
switch (flag) {
case 1:
log.getResults(result);
break;
case 2:
reg.checkExist(result);
break;
case 3:
reg.openLogin();
break;
default:
break;
}
}
}
At first I activate the regis function that works perfectly with the json class. Afterwards it suppose to activate checkExist if the cnt parameter is 0, which is 0. Then it is suppose to activate the json class again but it seems that it goes directly to openLogin function without going to the php file and activating it. Am I doing something wrong?
Related
everyone. I have an ArrayList of the data and a ListView to showing up the list of the data. Now what I want to do is rearrange the data when I press the button and sort the data in which data has the highest result.
Here is my code:
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
String[] dataDetail;
ArrayList<dataDetail> allDetail = new ArrayList<>();
ListView detailList;
final Context context = this;
final int min = 0;
final int max = 10;
final int random = new Random().nextInt((max - min) + 1) + min;
Button reorder = findViewById(R.id.arrangeId);
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detailList = findViewById(R.id.dataView);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
new GetData().execute();
}
private class GetData extends AsyncTask<Void, Void, ArrayList<dataDetail>> {
protected ArrayList<dataDetail> doInBackground(Void... voids) {
HttpURLConnection urlConnection;
InputStream in = null;
try {
URL url = new URL("http://10.0.2.2:8080/projectServer/DataDetailDB?getdata=true");
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String response = convertStreamToString(in);
System.out.println("Server response = " + response);
try {
JSONArray jsonArray = new JSONArray(response);
dataDetail = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
final String customerName = jsonArray.getJSONObject(i).get("customerName").toString();
final String carName = jsonArray.getJSONObject(i).get("carName").toString();
final String appointmentDate = jsonArray.getJSONObject(i).get("appointmentDate").toString();
final String email = jsonArray.getJSONObject(i).get("email").toString();
final String issueDescribe = jsonArray.getJSONObject(i).get("issueDescribe").toString();
final String timeForJob = jsonArray.getJSONObject(i).get("timeForJob").toString();
final String costForJob = jsonArray.getJSONObject(i).get("costForJob").toString();
final String reliableOnCar = jsonArray.getJSONObject(i).get("reliableOnCar").toString();
final String distanceJob = jsonArray.getJSONObject(i).get("distance").toString();
dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob);
allDetail.add(tData);
System.out.println("customername = " + customerName + "carname = " + carName + "appointmentdate = " + appointmentDate +
"email = " + email + "describe = " + issueDescribe + "time = " + timeForJob + "cost = " + costForJob + "reliable = " + reliableOnCar
+ "dis = " + distanceJob);
dataDetail [i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate;
reorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float finalResult = random * Float.parseFloat(timeForJob) + random * Float.parseFloat(reliableOnCar) +
random * Float.parseFloat(distanceJob) + random * Float.parseFloat(costForJob);
System.out.print("Test result " + finalResult + " ");
/* Trying to sort the data here which has the highest finalResult
* will going to the top of the list */
allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);
ArrayAdapter newList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
newList.setAdapter(theList);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayList<dataDetail> dataDetailArrayList) {
super.onPostExecute(dataDetailArrayList);
ArrayAdapter theList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
detailList.setAdapter(theList);
}
}
public String convertStreamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
But when I try to use sort I get the error says it's incompatible types.
allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);
The finalResult will do the calculation and get the final result for every data it retrieves from the database. And now I just want to reorder it automatically, This is the logcat:
Please anyone can help how can I do the rearrange for the listview?
Collections.sort() will work. Its your problem related to how your are storing your data in list
I am trying to post data to mysql data base and it post it. But now i am trying to apply check if the fields in activity are empty - and data isn't posted to database.
public class Accepter extends Activity implements OnClickListener{
private EditText etName,etAge,etCity,etContact,etQuantity;
private Spinner spBloodGroup;
private ImageView imCancel,imSave;
private String message = "POST";
private static String[] BLOOD_GROUPS = {"Select Blood Group","A +Ve","B +Ve","AB +Ve","O +Ve","A -Ve","B -Ve","AB -Ve","O -Ve"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accepter_entry_form);
etName = (EditText)findViewById(R.id.etNameAcc);
etAge = (EditText)findViewById(R.id.etAgeAcc);
etCity = (EditText)findViewById(R.id.etCityAcc);
etContact = (EditText)findViewById(R.id.etPhoneNoAcc);
etQuantity = (EditText)findViewById(R.id.etQuantityAcc);
spBloodGroup = (Spinner)findViewById(R.id.spBloodGroupAcc);
imCancel = (ImageView)findViewById(R.id.imCancelAcc);
imSave = (ImageView)findViewById(R.id.imSaveAcc);
imCancel.setOnClickListener(this);
imSave.setOnClickListener(this);
ArrayAdapter<String> bgAdapter = new ArrayAdapter<String>(Accepter.this,android.R.layout.simple_spinner_item,BLOOD_GROUPS);
bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBloodGroup.setAdapter(bgAdapter);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.imSaveAcc:
String name = etName.getText().toString();
String blood = spBloodGroup.getSelectedItem().toString();
String quantity = etQuantity.getText().toString();
String phone = etContact.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String city = etCity.getText().toString();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month= c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
if(name.length()>1 && blood.length()>1 && phone.length()>1 && age>15 && city.length()>1)
{
AccepterTask task = new AccepterTask(v.getContext());
task.execute(message ,name, blood, phone, String.valueOf(age),city,quantity,date);
etName.setText("");
spBloodGroup.setSelection(0);
etContact.setText("");
etAge.setText("");
etCity.setText("");
etQuantity.setText("");
finish();
}
else
{
Toast.makeText(Accepter.this, "Any field is empty or invalid", Toast.LENGTH_LONG).show();
}
break;
case R.id.imCancelAcc:
Intent i = new Intent(v.getContext(),MainView.class);
i.putExtra("type", "Accepter");
startActivity(i);
break;
}
}
public class AccepterTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String accepter_url = //"http://192.168.0.6/accepter.php";
"http://10.0.2.2/accepter.php";
private String s;
public AccepterTask(Context c)
{
context = c;
}
#Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String names = params[1];
final String blood = params[2];
final String phone = params[3];
final String age = params[4];
final String city = params[5];
final String quantity = params[6];
final String date = params[7];
list.add(new BasicNameValuePair("name", names));
list.add(new BasicNameValuePair("blood", blood));
list.add(new BasicNameValuePair("quantity", quantity));
list.add(new BasicNameValuePair("phone", phone));
list.add(new BasicNameValuePair("age", age));
list.add(new BasicNameValuePair("city", city));
list.add(new BasicNameValuePair("date", date));
json = jsonParser.makeHttpRequest(accepter_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
here for updates
I have image like this for example:
Recylerview2 inside Recylerview1
In this case:
If I click on the number 1 of list item, then recylerview2 will appear below a number 1
So my question is:
How can i do that? and this is my code.
Ive this code inside onBindViewHolder inside adapter.
fItemsHolder.mLinearReply.setVisibility(View.GONE);
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
And this is my asynctask:
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personalRoom.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
Log.w("notakomen", "notakomen: "+s);
}else{
Log.w("notakomen", "notakomen: "+s);
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
Log.e(TAG, "id_comment: " + id_comment
+ ", uid: " + uid
+ ", profile_name: " + profile_name
+ ", profile_photo: " + profile_photo
+ ", amount_of_comment: " + amount_of_comment
+ ", tgl_comment: " + tgl_comment);
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
feedItemsHolder.mNameReply.setText(profile_name);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mLinearReply.setVisibility(View.VISIBLE);
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
Try using this library: android-advancedrecyclerview
Check this example on how to use expandable recyclerview using this lib.
To use it, add the lib to your project by adding a dependency for it in the gradle.build file as:
dependencies {
compile ('com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.9.1#aar'){
transitive=true
}
}
I have several editText in my FirstActivity for CSV:
Button save;
CSV csv;
StringBuffer filePathc;
public final static String EXTRA_MESSAGE = "com.example.mapcard.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);
txtName= (EditText) findViewById(R.id.txtName);
txtCompany= (EditText) findViewById(R.id.txtCompany);
txtPhone= (EditText) findViewById(R.id.txtPhone);
txtMobile = (EditText) findViewById(R.id.txtMobile);
txtAddress = (EditText) findViewById(R.id.txtAddress);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtWebsite = (EditText) findViewById(R.id.txtWebsite);
txtTitle = (EditText) findViewById(R.id.txtTitle);
filePathc = new StringBuffer();
filePathc.append("/sdcard/Android/data/");
file = new File(filePathc+filename.toString());
csv = new CSV(file);
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
csv.writeHeader(txtName.getText().toString()+ ","
+txtCompany.getText().toString()
+ "," +txtPhone.getText().toString()
+ "," +txtMobile.getText().toString()
+ "," +txtAddress.getText().toString()
+ "," +txtEmail.getText().toString()
+ "," +txtWebsite.getText().toString()
+ "," +txtTitle.getText().toString());
Intent intent = new Intent(NewCard.this, Template.class);
intent.putExtra("name", Name);
intent.putExtra("company", Company);
intent.putExtra("phone", Phone);
intent.putExtra("mobile", Mobile);
intent.putExtra("address", Address);
intent.putExtra("email", Email);
intent.putExtra("website", Website);
intent.putExtra("title", Title);
startActivity(intent);
SecondActivity is to write this data into .csv file:
public class CSV {
private PrintWriter csvWriter;
private File file;
public CSV(File file) {
this.file = file;
}
public void writeHeader(String data) {
try {
if (data != null) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
File in directory is successfully created and data is inserted. I am trying to check the data like Name or Email, if it is duplicate/already recorded to not save into .csv and warn user with Toast "same data".
I think it is something to do with line:
try {
if (data != null) {
Your helps and suggestions are appreciated. Thank you.
Use following function
public boolean exist(String newData){
try {
FileInputStream fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
if(aDataRow.contains(newData))//<--check if data exists
return true;
}
txtData.setText(aBuffer);
myReader.close();
} catch (Exception e) {
}
return false;
}
And change your write header function to:
public void writeHeader(String data) {
try {
if (data != null&&!data.isEmpty()&&!exist(data)) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
data != null doesnt cover the case that the String is just empty, but not null. So basically you get "" from the textview by calling getText(). adding && !"".equals(data) should fix that problem
UPDATE
Well, there is a difference between an empty, and an uninitalized String. An uninitalized String means you declared it like String a; but nothing further.
If you use editText.getText() the editText will return a String which has been initialized but contains only what is currently in it. So basically if there is nothing in the editext it will return "".
And to sum this up:
String a;
null == "" // false
a == null // true
"".equals(editText.getTExt()) // true if the editext doesnt contain anything
I am trying to reverse geocode inside an AsyncTask to get the address of the current location. I want to set the EditText to the address as default when starting the activity. My problem is I am unable to do this in onPostExecute(), however, I can do it in runOnUiThread() inside doInBackground(). Why is this?
AsyncTask:
protected String doInBackground(Void ...params) {
Geocoder geocoder = new Geocoder(AddSpot.this, Locale.getDefault());
List<Address> addresses = null;
try {
// Call the synchronous getFromLocation() method by passing in the lat/long values.
addresses = geocoder.getFromLocation(currentLat, currentLng, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
System.out.println(addressText);
return addressText;
}
return null;
}
protected void onPostExecute(String address) {
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(address);
}
That does not work. However, when I stick a runOnUiThread in it, it works:
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
runOnUiThread(new Runnable()
{
#Override
public void run()
{
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(addressText);
}
});
System.out.println(addressText);
return addressText;
}
UPDATE
After some debugging it appears that onPostExecute is never called at all no matter what I do.
Things I have tried:
Log information inside onPostExecute: Does not appear
Remove the entire logic inside doInBackground so it's like this return "hello" : onPost still does not execute
You did not put #Override above onPostExecute. Also asynctask object must to be created inside UI thread.
EDIT: Your edittextis not updated, becauseit is consumedimidiatly after post execute is finished.
1) write EditText addrField; as class variable of activity class.
2) find reference to it in onCreate().
3) on your original onpostexecute should remain only addrField.setText(address);
there is my class, where textfields are updated from onPostexecute without any problems
public class AddToCheckActivity extends Activity {
// All static variables
private ProgressDialog pd = null;
// XML node keys
TextView active;
String addId = "";
JSONObject json = null;
ListView list;
String not_id, not_section, not_street, not_sqTotal, not_sqLiving,
not_sqKitchen, not_flat, not_floor, not_floors, not_text,
user_phone1, user_phone2, user_contact, not_region, not_district,
not_settle, not_price, not_photo, not_date, not_date_till, not_up,
not_premium, not_status, region_title, district_title,
settle_title, section_title, not_priceFor;
LinearLayout lin;
ImageView photo1;
ImageView photo2;
ImageView photo3;
Activity app;
ArrayList<String> photo_ids = new ArrayList<String>();
TextView address;
TextView date;
TextView date_till;
TextView description;
TextView district;
TextView flat;
TextView floor;
TextView floors;
TextView id;
TextView phone1;
TextView phone2;
TextView premium;
TextView region;
TextView section;
TextView settle;
TextView sqKitchen;
TextView sqLiving;
TextView sqTotal;
TextView uped;
TextView price;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aadd_addtocheck);
app = this;
lin = (LinearLayout) findViewById(R.id.lin);
address = (TextView) findViewById(R.id.tv_atc_address);
date = (TextView) findViewById(R.id.tv_atc_date);
date_till = (TextView) findViewById(R.id.tv_atc_date_till);
description = (TextView) findViewById(R.id.tv_atc_description);
district = (TextView) findViewById(R.id.tv_atc_dstrict);
flat = (TextView) findViewById(R.id.tv_atc_flat);
floor = (TextView) findViewById(R.id.tv_atc_floor);
floors = (TextView) findViewById(R.id.tv_atc_floors);
id = (TextView) findViewById(R.id.tv_atc_id);
phone1 = (TextView) findViewById(R.id.tv_atc_phone1);
phone2 = (TextView) findViewById(R.id.tv_atc_phone2);
premium = (TextView) findViewById(R.id.tv_atc_premium);
region = (TextView) findViewById(R.id.tv_atc_region);
section = (TextView) findViewById(R.id.tv_atc_section);
settle = (TextView) findViewById(R.id.tv_atc_settle);
sqKitchen = (TextView) findViewById(R.id.tv_atc_sqKitchen);
sqLiving = (TextView) findViewById(R.id.tv_atc_sqLiving);
sqTotal = (TextView) findViewById(R.id.tv_atc_sqTotal);
uped = (TextView) findViewById(R.id.tv_atc_uped);
price = (TextView) findViewById(R.id.tv_atc_price);
Bundle ex = getIntent().getExtras();
Log.d("Gues: ", "1");
Button back_button = (Button) findViewById(R.id.back_btn);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
pd = new ProgressDialog(app);
pd.setOwnerActivity(app);
pd.setTitle("Идет загрузка...");
pd.setCancelable(true);
if (ex != null) {
addId = ex.getString("add_id");
Log.d("Gues: ", "2");
not_id = not_priceFor = not_section = not_street = not_sqTotal = not_sqLiving = not_sqKitchen = not_flat = not_floor = not_floors = not_text = user_phone1 = user_phone2 = user_contact = not_region = not_district = not_settle = not_price = not_photo = not_date = not_date_till = not_up = not_premium = not_status = region_title = district_title = settle_title = section_title = "";
Log.d("Gues: ", "3");
GetAdd addvert = new GetAdd();
addvert.execute();
}
}
public void onClickBtnAtcDelete(View v) {
Thread t = new Thread(new Runnable() {
public void run() {
UserFunctions u = new UserFunctions();
u.deleteAdd(not_id);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
public void btnAtcEdit(View v) {
Intent i = new Intent(getApplicationContext(), AddSaveActivity.class);
final BitmapDrawable bitmapDrawable1 = (BitmapDrawable) photo1
.getDrawable();
final Bitmap yourBitmap1 = bitmapDrawable1.getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
yourBitmap1.compress(Bitmap.CompressFormat.PNG, 90, stream1);
byte[] imm1 = stream1.toByteArray();
final BitmapDrawable bitmapDrawable2 = (BitmapDrawable) photo2
.getDrawable();
final Bitmap yourBitmap2 = bitmapDrawable2.getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
yourBitmap2.compress(Bitmap.CompressFormat.PNG, 90, stream2);
byte[] imm2 = stream2.toByteArray();
final BitmapDrawable bitmapDrawable3 = (BitmapDrawable) photo3
.getDrawable();
final Bitmap yourBitmap3 = bitmapDrawable3.getBitmap();
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
yourBitmap3.compress(Bitmap.CompressFormat.PNG, 90, stream3);
byte[] imm3 = stream3.toByteArray();
i.putExtra("photo1", imm1);
i.putExtra("photo2", imm2);
i.putExtra("photo3", imm3);
i.putStringArrayListExtra("photo_ids", photo_ids);
i.putExtra("not_id", not_id);
i.putExtra("not_section", not_section);
i.putExtra("not_street", not_street);
i.putExtra("not_sqTotal", not_sqTotal);
i.putExtra("not_sqLiving", not_sqLiving);
i.putExtra("not_sqKitchen", not_sqKitchen);
i.putExtra("not_flat", not_flat);
i.putExtra("not_floor", not_floor);
i.putExtra("not_floors", not_floors);
i.putExtra("not_text", not_text);
i.putExtra("not_phone1", user_phone1);
i.putExtra("not_phone2", user_phone2);
i.putExtra("not_region", not_region);
i.putExtra("not_district", not_district);
i.putExtra("not_settle", not_settle);
i.putExtra("not_price", not_price);
i.putExtra("not_date", not_date);
i.putExtra("not_date_till", not_date_till);
i.putExtra("region_title", region_title);
i.putExtra("district_title", district_title);
i.putExtra("section_title", section_title);
i.putExtra("settle_title", settle_title);
i.putExtra("not_priceFor", not_priceFor);
startActivity(i);
}
public void onClickAtcGoToChooser(View v) {
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
class GetAdd extends AsyncTask<Integer, Void, JSONObject> {
// private ProgressDialog pd = null;
private int op = 0;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(app);
// pd.setOwnerActivity(app);
// pd.setTitle("Идет загрузка...");
// pd.setCancelable(true);
pd.show();
}
#Override
protected JSONObject doInBackground(Integer... params) {
// TODO Auto-generated method stub
UserFunctions u = new UserFunctions();
// json = u.getNewAdd(addId);
return u.getNewAdd(addId);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
active = (TextView) findViewById(R.id.tv_atc_active);
photo1 = (ImageView) findViewById(R.id.imageP1);
photo2 = (ImageView) findViewById(R.id.imageP2);
photo3 = (ImageView) findViewById(R.id.imageP3);
ImageLoader imi = new ImageLoader(app.getApplicationContext());
if (result != null && result.has("not_id")) {
try {
Log.d("Gues: ",
"5_1 to status " + result.getString("not_status"));
// active.setText(json.getString("not_status")+"");
not_status = ("" + result.getString("not_status"));
not_region = ("" + result.getString("not_region"));
not_district = ("" + result.getString("not_district"));
not_settle = ("" + result.getString("not_settle"));
not_section = ("" + result.getString("not_section"));
not_street = (result.getString("not_street"));
not_date = (result.getString("not_date"));
not_price = (result.getString("not_price"));
not_date_till = (result.getString("not_date_till"));
not_text = (result.getString("not_text"));
district_title = (result.getString("district_title"));
not_flat = (result.getString("not_flat"));
not_floor = (result.getString("not_floor"));
not_floors = (result.getString("not_floors"));
not_id = (result.getString("not_id"));
user_phone1 = (result.getString("user_phone1"));
user_phone2 = (result.getString("user_phone2"));
not_premium = (result.getString("not_premium"));
region_title = (result.getString("region_title"));
section_title = (result.getString("section_title"));
settle_title = (result.getString("settle_title"));
not_sqKitchen = (result.getString("not_sqKitchen"));
not_sqTotal = (result.getString("not_sqTotal"));
not_sqLiving = (result.getString("not_sqLiving"));
not_up = (result.getString("not_up"));
LinearLayout l = (LinearLayout) findViewById(R.id.appDetail);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
l.setVisibility(View.GONE);
}
not_priceFor = (result.getString("not_priceFor"));
String link1, link2, link3;
link1 = link2 = link3 = "";
JSONArray ar = result.getJSONArray("not_photos");
JSONArray pp = result.getJSONArray("photo_ids");
Log.d("ATC photo_ids", "-" + pp.length());
Log.d("ATC result", result.toString());
Log.d("ATC result pp", pp.toString());
Log.d("ATC result ppelement", pp.getString(0).toString());
for (int i = 0; i < pp.length(); i++) {
Log.d("ATC photo_ids pos", "-" + i);
Log.d("ATC result ppelement iter", pp.getString(i)
.toString());
photo_ids.add(pp.getString(i).toString());
}
// String[] ph = new String[3];
// for (int i =0; i< 3;i++){
// ph[i]=ar.getJSONObject(i).toString();
// }
imi.DisplayImage(ar.getString(0).toString(), photo1);
imi.DisplayImage(ar.getString(1).toString(), photo2);
imi.DisplayImage(ar.getString(2).toString(), photo3);
Log.d("Gues: ", "5_5");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Integer.parseInt(not_status) == 0) {
active.setText("Неактивно");
} else {
active.setText("Активно");
}
address.setText("Улица: " + not_street);
date.setText("Создано: " + not_date);
date_till.setText("Действительно до: " + not_date_till);
description.setText("Подробности объявления: " + "\n"
+ not_text);
district.setText("Город/поселок: " + district_title);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
flat.setText("Машиномест: " + not_flat);
} else
flat.setText("Количество комнат: " + not_flat);
floor.setText("Этаж: " + not_floor);
floors.setText("Этажность: " + not_floors);
id.setText("ID: " + not_id + " ");
phone1.setText("Телефон: " + user_phone1);
phone2.setText("Телефон: " + user_phone2);
if (Integer.parseInt(not_premium) == 0) {
premium.setText("Обычное");
} else {
premium.setText(" Примиумное");
}
region.setText("Регион: " + region_title);
section.setText("В рубрике: " + section_title);
settle.setText("Район: " + settle_title);
sqKitchen.setText("Площадь кухни: " + not_sqKitchen);
sqTotal.setText("Общая площадь: " + not_sqTotal);
sqLiving.setText("Жилая площадь: " + not_sqLiving);
if (Integer.parseInt(not_up) == 0) {
uped.setText("");
} else {
uped.setText(" Поднятое ");
}
String priceT = "";
if (Integer.parseInt(not_priceFor) == 1)
priceT = "за все";
else if (Integer.parseInt(not_priceFor) == 2)
priceT = "за кв.м";
else if (Integer.parseInt(not_priceFor) == 3)
priceT = "за месяц";
else if (Integer.parseInt(not_priceFor) == 4)
priceT = "в сутки";
else if (Integer.parseInt(not_priceFor) == 5)
priceT = "в час";
else if (Integer.parseInt(not_priceFor) == 6)
priceT = "за кв.м./месяц";
else if (Integer.parseInt(not_priceFor) == 7)
priceT = "за сотку";
price.setText("Цена: " + not_price + " грн. " + priceT);
lin.setVisibility(View.VISIBLE);
} else {
error();
}
}
}
}
PS: t oavoid problems in future, don't put UI operations in any part of try{}