Return button to previous activity with BaseAdapter - android

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.

if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

Related

Unable to get user id from JSON using shared preferences

JSON DATA
{
VerifiedMember: [{ user_id: "23", first_name: "karan", phone: "" }],
success: 1,
message: "success"
}
Login Activity Class
public class NewLogin extends AppCompatActivity {
private static final String PREFER_NAME = "Reg";
Button btnLogin;
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
SharedPreferences sharedPreferences;
// User Session Manager Class
UserSessionManager session;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
// User Session Manager
session = new UserSessionManager(getApplicationContext());
sharedPreferences = getApplication().getSharedPreferences("KEY", Context.MODE_PRIVATE);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
private class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
#Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<>();
// Get username, password from EditText
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String url = "xxxx.xxx";
JSONObject json;
int successValue = 0;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "POST", params);
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("username")) {
uName = sharedPreferences.getString("username", "");
}
if (sharedPreferences.contains("password")) {
uPassword = sharedPreferences.getString("password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession("username", "password");
} else {
}
}else{
}
Log.d("TESS :: ", json.toString());
successValue = json.getInt("success");
Log.d("Success Response :: ", String.valueOf(successValue));
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return String.valueOf(successValue);
}
protected void onPostExecute(String jsonstring) {
pDialog.dismiss();
if (jsonstring.equals("1")) {
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
finish();
} else {
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
}
}
}
Sample activity:
public class Sample extends AppCompatActivity {
private static final String URL_DATA = "xxx.xxx";
// User Session Manager Class
UserSessionManager session;
LinearLayout linearLayout;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private List<Data_SAerver> data_sAervers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
// Session class instance
session = new UserSessionManager(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
loadRecyclerViewData();
swipeRefreshLayout.setRefreshing(false);
}
});
swipeRefreshLayout.setColorScheme(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
linearLayout = (LinearLayout) findViewById(R.id.linaralayout1);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Sample.this, Post_data_Activity.class);
startActivity(i);
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
data_sAervers = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
String filename = "";
String filetype = "";
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray posts = jsonObject.getJSONArray("posts");
if (posts != null && posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject fileObj = posts.getJSONObject(i);
String fName = fileObj.getString("firstname");
String created_at = fileObj.getString("created_at");
String post_desc = fileObj.getString("post_desc");
Log.e("Details", fName + "" + created_at + "" + post_desc);
JSONArray files = fileObj.getJSONArray("files");
if (files != null && files.length() > 0) {
for (int j = 0; j < files.length(); j++) {
JSONObject Jsonfilename = files.getJSONObject(j);
filename = Jsonfilename.getString("file_name");
filetype = Jsonfilename.getString("file_type");
if (filetype.equalsIgnoreCase("2")) {
filename = "xxx.xxx" + filename;
} else if(filetype.equalsIgnoreCase("1")) {
filename = "xxx.xxx" + filename;
}
Log.e("Files", "" + filename);
}
} else {
filename = "";
filetype = "";
}
Data_SAerver item = new Data_SAerver(fName, created_at, post_desc, filename, filetype);
data_sAervers.add(item);
}
}
adapter = new MyAdapter(data_sAervers, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuLogout:
session.logoutUser();
/*startActivity(new Intent(this, NewLogin.class));
break;*/
}
return true;
}
}
MyAdapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Data_SAerver> data_sAervers;
private Context context;
public MyAdapter(List<Data_SAerver> data_sAervers, Context context) {
this.data_sAervers = data_sAervers;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample, parent, false);
return new ViewHolder(v, context);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data_SAerver data_sAerver = data_sAervers.get(position);
holder.firstname.setText(data_sAerver.getFirstname());
holder.created_at.setText(data_sAerver.getCreated_at());
holder.post_desc.setText(data_sAerver.getPost_desc());
holder.filepathurl.setText(data_sAerver.getfilepath());
if (data_sAerver.getFiletype().equals("1")) {
holder.files.setVisibility(View.VISIBLE);
Picasso.with(context).load(data_sAerver.getfilepath()).resize(736, 1128).onlyScaleDown().into(holder.files);
holder.playvideo.setVisibility(View.GONE);
} else {
if (data_sAerver.getFiletype().equals("2")) {
holder.playvideo.setVisibility(View.VISIBLE);
holder.files.setVisibility(View.GONE);
holder.playvideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent play = new Intent(context, PlayVideo.class);
play.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
play.putExtra("url", data_sAerver.getfilepath());
context.startActivity(play);
}
});
}
}
}
#Override
public int getItemCount() {
return data_sAervers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// User Session Manager Class
UserSessionManager session;
public TextView firstname, commenttext;
public TextView created_at;
public TextView post_desc;
public ImageView files;
public LinearLayout comment_linear_layout;
public TextView comment_btn;
public TextView filepathurl;
public TextView playvideo;
// private TextView editTextUserName;
public TextView onlinefirstname;
Context con;
public ViewHolder(View itemView, Context context) {
super(itemView);
filepathurl = (TextView) itemView.findViewById(R.id.filepathurl);
filepathurl.setVisibility(View.GONE);
// editTextUserName = (TextView) itemView.findViewById(R.id.editTextUserrName);
playvideo = (TextView) itemView.findViewById(R.id.playvideo);
firstname = (TextView) itemView.findViewById(R.id.firstname);
created_at = (TextView) itemView.findViewById(R.id.created_at);
post_desc = (TextView) itemView.findViewById(R.id.post_desc);
files = (ImageView) itemView.findViewById(R.id.image_files);
con = context;
// onlinefirstname = (TextView)itemView.findViewById(R.id.online_user_firstname);
SparkButton sparkButton = (SparkButton) itemView.findViewById(R.id.star_button1);
sparkButton.setChecked(false);
comment_btn = (TextView) itemView.findViewById(R.id.comment_btn);
comment_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(con, Popup_layout.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
con.startActivity(i);
}
});
}
}
}
UserSessionManager:
public class UserSessionManager {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "username";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "firstname";
// password
public static final String KEY_PASSWORD = "password";
// Constructor
public UserSessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassord){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, uName);
// Storing email in pref
editor.putString(KEY_PASSWORD, uPassord);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Sample.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, NewLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
Here I am not able to get user_id using shared preference. Please help me how to get it.
In onPostExecute try this you will get User ID
try {
String userid;
JSONObject ob = new JSONObject(jsonstring);
JSONArray arr = ob.getJSONArray("VerifiedMember");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
userid=obj.getString("user_id");
}
} catch (Exception e) {
}
You can use this pojo generator
http://www.jsonschema2pojo.org/
For parsing you can use google's gson library or jackson parser is also good.
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html

How to add adapter2 with asynctask inside adapter1

I've this adapter class :
public class NoteFeedListAdapter extends RecyclerView.Adapter<feedItemsHolder>{
private Activity activity;
private LayoutInflater inflater;
private List<NoteFeedItem> feedItems;
private List<CommentModel> commentItems;
private NoteCommentListAdapter adapter;
private RecyclerView mRecyclerView;
ImageLoader imageLoader = NoteAppController.getInstance().getImageLoader();
private static final String URL_LIST_VIEW_COMMENT = "http://url.com";
private int level = 0;
private Context mContext;
public NoteFeedListAdapter(Context context, List<NoteFeedItem> feedItems) {
this.feedItems = feedItems;
this.mContext = context;
}
public feedItemsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feed_item, null);
feedItemsHolder mh = new feedItemsHolder(v);
return mh;
}
public void onBindViewHolder(final feedItemsHolder fItemsHolder, final int i) {
final NoteFeedItem item = feedItems.get(i);
fItemsHolder.setLevel(item.getLevel());
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
and Inside onBindViewHolder :
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this code is what I used to call asyntask but result from asynctask cannot be shown in this adapter
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);
}
if(item.getLevel() == Level.LEVEL_ONE){
level = Level.LEVEL_TWO;
}else if(item.getLevel() == Level.LEVEL_TWO){
level = Level.LEVEL_THREE;
}
}
public int getItemCount() {
return (null != feedItems ? feedItems.size() : 0);
}
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.personal.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();
}else{
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
Toast.makeText(mContext, id_note, Toast.LENGTH_SHORT).show();
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");
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);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
The problem is that I wanna add data from Asynctask and shown on another adapter. But how can i do that? please help. view from another adapter couldn't show with this code.

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

how to display dynamic spinner values in android

In the code below, I took two spinners. One is for brand and other for model. But data is not being displaying in spinner. It is not showing any errors but dropdown is also not shown.
Can any one help me?
What is the mistake in the code?
Java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
private RelativeLayout mRel_Ownview,mRel_publicview;
private LinearLayout mLin_Stock,mLin_Contact;
private TextView mTxt_OwnView,mTxt_PublicView;
private Map<String, String> BrandMap = new HashMap<String, String>();
private RangeSeekBar<Integer> seekBar;
private RangeSeekBar<Integer> seekBar1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
actionBar.setTitle("DEVINE MECHINES");
SharedPreferences userPreference = getActivity().getSharedPreferences("UserDate", Context.MODE_PRIVATE);
userId=userPreference.getString("MYID", null);
companyId=userPreference.getString("companyId",null);
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
seekBar = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
seekBar1 = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar1.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin1);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax1);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
mTxt_OwnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_publicview.setVisibility(View.GONE);
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.text_white));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.light_blue));
mRel_Ownview.setVisibility(View.VISIBLE);
}
});
mTxt_PublicView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_Ownview.setVisibility(View.GONE);
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.text_white));
mRel_publicview.setVisibility(View.VISIBLE);
}
});
String selectedBrandId = BrandMap.get(String.valueOf(spinner1.getSelectedItem()));
// System.out.print(url);
mLin_Stock=(LinearLayout)rootView.findViewById(R.id.stock);
mLin_Stock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment =new StockFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
mLin_Contact =(LinearLayout)rootView.findViewById(R.id.contacts);
mLin_Contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getLead();
fragment = new ContactFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
getLead();
}
});
// add RangeSeekBar to pre-defined layout
ViewGroup layout = (ViewGroup) rootView.findViewById(R.id.layout_seek);
layout.addView(seekBar);
ViewGroup layout1 = (ViewGroup) rootView.findViewById(R.id.layout_seek1);
layout1.addView(seekBar1);
getBrands();
getModels();
return rootView;
}
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url", "" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
//Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.i("Brand_result","Now" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
Log.i("listbrands", "List Brands" + listBrands);
/* for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}*/
spinner_fn();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
Log.i("Result","Brand Result"+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
/*ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
listBrands_String, android.R.layout.simple_spinner_item);*/
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
//dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void getLead()
{
String url = URLBuilder.getLeadUrl();
String json = JSONBuilder.getJSONLead(userId, companyId);
SendToServerTask task = new SendToServerTask(getActivity());
task.execute(url, json);
}
private void setLead(String json)
{
ObjectMapper objectMapper = new ObjectMapper();
try
{
LeadResult result_object = objectMapper.readValue(json, LeadResult.class);
String lead_result = result_object.getRESULT();
Log.d("lead_result","" + lead_result);
if (lead_result.equals("SUCCESS"))
{
list=result_object.getUSERS();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTask extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTask(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setLead(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}

listview does not updates

I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}

Categories

Resources