****Working code posted****
I am trying to update buttons where the text will be dynamically programmed from an ArrayList. The data is being retrieved from mySQL. I can get the data in and fill the array with what I need (familyMemberArray). However for some reason when the information is gathered, the program does not go on to implementing the "trending" array or the rest of the layout programming, after the array information has been produced.
I need to formulate the data first so I know how big the array is to create the amount of buttons necessary. If I call in a basic String array it populates the buttons just fine. I remember being stuck on this problem on a uni project and ended up giving up because I just could not get it to work and time was ticking. Please put me out of my misery
public class TrendingMealsFragment extends Fragment {
private TableRow tr;
//SQLite Database
private static final String SELECT_SQL = "SELECT * FROM family_account";
private SQLiteDatabase db;
private Cursor c;
private static final String DATABASE_NAME = "FamVsFam.db";
// Logging
private final String TAG = this.getClass().getName();
private static final String EXTRA_CHALLENGE_ID = "boo.famvsfam.challenge_id";
//Results
private JSONArray resultFamilyMember;
private String dbID;
public static final String JSON_ARRAY = "result";
private List<String> familyMemberArray;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openDatabase();
setHasOptionsMenu(true);
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
getRecords();
}
protected void openDatabase() {
db = getActivity().openOrCreateDatabase(DATABASE_NAME, android.content.Context.MODE_PRIVATE, null); // db = SQLiteDatabase.openOrCreateDatabase("FamVsFam", Context.MODE_PRIVATE, null);
}
protected void getRecords() {
dbID = c.getString(0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getData();
/** Declaring an ArrayAdapter to set items to ListView */
familyMemberArray = new ArrayList<>();
//Menu
setHasOptionsMenu(true);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
View view = inflater.inflate(R.layout.activity_resturants, container, false);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar();
/**
ArrayList<String> trending1 = new ArrayList<String>() {
{
add("one");
add("two");
add("three");
add("four");
add("five");
add("six");
add("seven");
add("eight");
add("nine");
add("ten");
add("eleven");
}
};*/
ArrayList<String> trending = new ArrayList<String>() {
{
for(int i = 0; i < familyMemberArray.size() ; i++){
add(familyMemberArray.get(i));
}}
};
// LAYOUT SETTING 1
RelativeLayout root = new RelativeLayout(getActivity());
// root.setId(Integer.parseInt(MEAL_SELECTION_ID));
LayoutParams param1 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
root.setFitsSystemWindows(true);
}
root.setLayoutParams(param1);
//LAYOUT SETTINGS 2 - TOP BANNER - WITH PAGE HEADING
RelativeLayout rLayout1 = new RelativeLayout(getActivity());
LayoutParams param2 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
float topBannerDim = getResources().getDimension(R.dimen.top_banner);
param2.height = (int) topBannerDim;
param2.addRule(RelativeLayout.BELOW, root.getId());
int ele = (int) getResources().getDimension(R.dimen.elevation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
rLayout1.setElevation(ele);
}
rLayout1.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout1.setLayoutParams(param2);
//TEXT VIEW
TextView text1 = new TextView(getActivity());
text1.setText(R.string.diet_req);
LayoutParams param3 = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
param3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
text1.setTextColor(Color.parseColor("#8A1F1D"));
text1.setTypeface(Typeface.DEFAULT_BOLD);
text1.setLayoutParams(param3);
//LAYOUT SETTINGS 4
RelativeLayout rLayout4 = new RelativeLayout(getActivity());
LayoutParams param5 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
topBannerDim = getResources().getDimension(R.dimen.top_banner);
param5.height = (int) topBannerDim;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
param5.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.ALIGN_START);
}
param5.addRule(RelativeLayout.BELOW, rLayout1.getId());
rLayout4.setId(R.id.id_relative_4);
rLayout4.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout4.setLayoutParams(param5);
//LAYOUT SETTINGS 5
TableLayout rLayout5 = new TableLayout(getActivity());
rLayout5.setOrientation(TableLayout.VERTICAL);
LayoutParams param7 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
param7.addRule(RelativeLayout.BELOW, rLayout4.getId());
rLayout5.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout5.setLayoutParams(param7);
// List<ToggleButton> togButtStore = new ArrayList<ToggleButton>();
int i = 0;
while (i < trending.size()) {
if (i % 3 == 0) {
tr = new TableRow(getActivity());
rLayout5.addView(tr);
}
ToggleButton toggleBtn = new ToggleButton(getActivity());
toggleBtn.setText(trending.get(i));
toggleBtn.setId(i);
toggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// The toggle is disabled
}
}
});
tr.addView(toggleBtn);
i++;
}
//LAYOUT SETTINGS 6
FrameLayout youBeenFramed = new FrameLayout(getActivity());
LayoutParams param8 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
param8.addRule(RelativeLayout.BELOW, rLayout5.getId());
youBeenFramed.setBackgroundColor(Color.parseColor("#EEEBAA"));
root.addView(youBeenFramed);
root.addView(rLayout1);
rLayout1.addView(text1);
root.addView(rLayout4);
root.addView(rLayout5);
getActivity().setContentView(root);
return view;
}
public void getData() {
//// TODO: 03/08/2016 Progress Dialogs : on getting data
// final ProgressDialog loading = ProgressDialog.show(getActivity(), "Loading Data", "Please wait...", false, false);
StringRequest strReq = new StringRequest(Request.Method.POST,
PHPConfigURLS.URL_ALL_FAMILY_MEMBERS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
JSONObject j = null;
try {
// loading.dismiss();
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFamilyMember = j.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDBFamilyName(resultFamilyMember);
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
String id = dbID;
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
// params.put("email", email);
// params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(strReq);
}
private void getDBFamilyName(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
FamilyAccount familyMember = new FamilyAccount();
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
familyMember = new FamilyAccount();
familyMember.setName(json.getString("name"));
familyMember.setID(json.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the title of the challenge to array list
familyMemberArray.add(familyMember.getName());
}
}
}
Thanks in advance
for some reason when the information is gathered, the program does not go on to implementing the "trending" array or the rest of the layout programming, after the array information has been produced.
That's because the layout doesn't "dynamically" update when you call this when the request finishes.
familyMemberArray.add(familyMember.getName());
You'll have to clear the view, and redo all the view adding again, or "extract" all the view generation code into it's own method that you can call with the parameter of your ArrayList.
Basically, everything between // LAYOUT SETTING 1 and return view (non-inclusive) needs to be moved into a public void generateView(ArrayList<String> familyMemberArray) method that can optionally return the root View that was generated, if necessary.
Then, at the end of getFamilyName(), outside the loop, call that method with your ArrayList.
I need to formulate the data first so I know how big the array is to create the amount of buttons necessary.
I'm not sure I see where you are doing that. Unless you mean here
while (i < trending.size()) {
Which, instead, trending is an entirely different list reference than familyMemberArray, so it won't update either. Though, it contains the exact same data?
ArrayList<String> trending = new ArrayList<String>() {
{
for(int i = 0; i < familyMemberArray.size() ; i++){
add(familyMemberArray.get(i));
}}
};
That block of code looks a bit odd, considering the ArrayList constructor already provides that functionality
ArrayList<String> trending = new ArrayList<String>(familyMemberArray);
*****WORKING CODE****** Credit to cricket_007
FIELDS
public class TrendingMealsFragment extends Fragment {
// Logging
private final String TAG = this.getClass().getName();
//Results
private JSONArray resultFamilyMember;
public static final String JSON_ARRAY = "result";
private ArrayList<String> familyMemberArray;
//Layout
private TableRow tr;
OnCreateView()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_resturants, container, false);
generateView(familyMemberArray);
getData();
return view;
}
GetData()
public void getData() {
StringRequest strReq = new StringRequest(Request.Method.POST,
PHPConfigURLS.URL_ALL_FAMILY_MEMBERS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFamilyMember = j.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDBFamilyName(resultFamilyMember);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
String id = dbID;
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(strReq);
}
getDBFamilyName()
private void getDBFamilyName(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
FamilyAccount familyMember = new FamilyAccount();
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
familyMember = new FamilyAccount();
familyMember.setName(json.getString("name"));
familyMember.setID(json.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the title of the challenge to array list
familyMemberArray.add(familyMember.getName());
generateView(familyMemberArray);
}
}
generateView()
public View generateView(ArrayList<String> familyMemberArray) {
...
rLayout5.setLayoutParams(param7);
//Create Buttons
int i = 0;
while (i < familyMemberArray.size()) {
if (i % 3 == 0) {
tr = new TableRow(getActivity());
rLayout5.addView(tr);
}
ToggleButton toggleBtn = new ToggleButton(getActivity());
toggleBtn.setText(familyMemberArray.get(i));
toggleBtn.setId(i);
toggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// The toggle is disabled
}
}
});
tr.addView(toggleBtn);
i++;
}
...
root.addView(rLayout5);
getActivity().setContentView(root);
return root;
}
}
Related
I am developing Android app which obtains information about restaurants from server and shows them in RecyclerView. When first package of information is obtained from server, everything works as expected, but, when I change search criteria and request new package of information from server, RecyclerView becomes blank. I used Toasts to debug what is coming from server and I am convinced that data is properly formatted. Also, variables that are used for accepting the data are also properly handled in code, according to my observations. Do you maybe know why my RecyclerView is empty when second package of data should be shown? Here is the code.
AfterLoginActivity.java
public class AfterLoginActivity extends AppCompatActivity {
/* interface main elements */
LinearLayout afterLoginLayout;
LinearLayout restaurantListLayout;
EditText restaurantEditText;
Button findRestaurantButton;
LoadingDialog loadingDialog;
AlphaAnimation loadingAnimation;
RecyclerView restaurantsRecyclerView;
int recycler_set = 0;
Button signOutButton;
GoogleSignInClient mGoogleSignInClient;
MyAdapter myAdapter = null;
/* server-client communication data */
public static String UploadUrl = "https://gdedakliknem.com/klopator.php";
public static String[] received;
String restaurants[] = new String[40];
String logos_as_strings[] = new String[40];
Bitmap logos[] = new Bitmap[40];
int num_of_elements = 0;
int data_received = 0;
/* user data */
String person_email;
String person_name;
String restaurant;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
/* interface main elements */
afterLoginLayout = findViewById(R.id.afterLoginLayout);
restaurantListLayout = findViewById(R.id.restaurantListLayout);
restaurantEditText = findViewById(R.id.restaurantEditText);
findRestaurantButton = findViewById(R.id.findRestaurantButton);
restaurantsRecyclerView = findViewById(R.id.restaurantsRecyclerView);
signOutButton = findViewById(R.id.signOutButton);
loadingAnimation = new AlphaAnimation(1F, 0.8F);
loadingDialog = new LoadingDialog(AfterLoginActivity.this);
/* UPDATING INTERFACE ELEMENTS */
/* execution thread */
final Handler handler = new Handler();
final int delay = 2000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
/* check if recycler view is set */
if(recycler_set == 0){
/* if not, check if there is data to fil it with */
if(data_received == 1){
/* convert received strings to images */
for(int i = 0; i < num_of_elements; i++){
logos[i] = stringToBitmap(logos_as_strings[i]);
}
/* fill interface elements */
loadingDialog.dismissDialog();
myAdapter = new MyAdapter(AfterLoginActivity.this, restaurants, logos, num_of_elements);
restaurantsRecyclerView.setAdapter(myAdapter);
restaurantsRecyclerView.setLayoutManager(new LinearLayoutManager(AfterLoginActivity.this));
afterLoginLayout.setVisibility(View.GONE);
restaurantListLayout.setVisibility(View.VISIBLE);
recycler_set = 1;
}
}
handler.postDelayed(this, delay);
}
}, delay);
/* catch restaurant name from user's entry */
findRestaurantButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restaurant = restaurantEditText.getText().toString();
if(!restaurant.isEmpty()){
view.startAnimation(loadingAnimation);
loadingDialog.startLoadingDialog();
sendRequest();
} else{
Toast.makeText(AfterLoginActivity.this, "Unesite naziv restorana!", Toast.LENGTH_LONG).show();
}
}
});
/* enable signing out */
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.signOutButton:
signOut();
break;
}
}
});
/* obtaining email */
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
person_email = acct.getEmail();
person_name = acct.getDisplayName();
}
}
#Override
public void onBackPressed() {
afterLoginLayout.setVisibility(View.VISIBLE);
restaurantsRecyclerView.setVisibility(View.GONE);
data_received = 0;
recycler_set = 0;
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AfterLoginActivity.this, "Signed out", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if (Response.equals("Restaurant not found")){
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Uneti restoran ne postoji u sistemu! Proverite da li ste dobro napisali naziv", Toast.LENGTH_LONG).show();
} else{
received = Response.split(";");
if (received.length > 0){
data_received = 1;
num_of_elements = received.length / 2;
//Toast.makeText(getApplicationContext(), "num of elements: " + num_of_elements, Toast.LENGTH_LONG).show();
for(int i = 0; i < num_of_elements; i++){
logos_as_strings[i] = received[i*2];
restaurants[i] = received[i*2+1];
//Toast.makeText(getApplicationContext(), "restaurants: " + restaurants, Toast.LENGTH_LONG).show();
}
} else{
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Greška u prijemu", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(final VolleyError error) {
//volleyError = error;
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Toast.makeText(getApplicationContext(), "get params", Toast.LENGTH_LONG).show();
Map<String, String> params = new HashMap<>();
params.put("control", "find_restaurant");
params.put("restaurant", restaurant);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AfterLoginActivity.this);
requestQueue.add(stringRequest);
}
public static Bitmap stringToBitmap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
} catch (Exception e) {
e.getMessage();
return null;
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
String restaurants[];
Bitmap logos[];
Context context;
int num_of_elements;
public MyAdapter(Context ct, String rests[], Bitmap lgs[], int num){
context = ct;
restaurants = rests;
logos = lgs;
num_of_elements = num;
Toast.makeText(context, Integer.toString(restaurants.length), Toast.LENGTH_LONG).show();
for(int i = 0; i < restaurants.length; i++){
Toast.makeText(context, restaurants[i], Toast.LENGTH_SHORT).show();
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.restaurant_item_layout, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
holder.restaurantNameTextView.setText(restaurants[position]);
holder.restaurantLogoImageView.setImageBitmap(logos[position]);
holder.restaurantItemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AfterPickingRestaurantActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
logos[position].compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("byteArray", bs.toByteArray());
intent.putExtra("picked_restaurant_name", restaurants[position]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
/*
int i = 0;
if (restaurants != null){
while(restaurants[i] != null){
i++;
}
} else{
i = restaurants.length;
}
return i;
*/
return num_of_elements;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView restaurantNameTextView;
ImageView restaurantLogoImageView;
LinearLayout restaurantItemLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
restaurantNameTextView = itemView.findViewById(R.id.restaurantNameTextView);
restaurantLogoImageView = itemView.findViewById(R.id.restaurantLogoImageView);
restaurantItemLayout = itemView.findViewById(R.id.restaurantItemLayout);
}
}
Add this lines after getting new data
myAdapter.notifyDataSetChanged()
Your Adapter Already set with RecyclerView in OnCreate Method.
so when'er you click on findRestaurantButton you just get Resturent data from server but collected data not pass in adapter so thats why to getting blank adapter..
Just put this line in your onResponse after set data in array..
myAdapter.notifyDataSetChanged()
I found out where is the mistake. If you take a look at the section where overriding of back button click is happening, I by mistake set to GONE recyclerView itself:
restaurantsRecyclerView.setVisibility(View.GONE);
instead of LinearLayout in which recyclerView is contained. Desired action was:
restaurantListLayout.setVisibility(View.GONE);
P.S. Everything works without calling notifyDataSetChanged(), I just create a new instance of myAdapater each time when I receive new data. I hope Garbage Collector is doing its job :)
Thanks everyone on help!
I am having this issue for some time now, when I retrieved data from a database using volley and then show it in a recycler view, if the items are 8 or less than 8 then it shows them without any problem, but if I retrieve more than 8 items from database then the activity closes/crashes and goes back to the main activity. I don't get any error in the run console in android studio. I am retrieving 3 things from database for a single item, 2 strings and an image. I don't think the error is in the php file which is used to get the data as that I have checked and it retrieves without any issue. I have searched android documentation of recycler view but couldn't find anything
NOTE: I am getting image as string and then converting to bitmap.
if there is anything else needed then I can provide them without any issue.
the code is below:
Method which is used to call the recycler view activity which has problems.
public void onViewAttendanceButtonClick(int position, String courseCode,
String courseName, String batchName) {
if (MainActivity.teacherData != null) {
seeAttendanceDetails(MainActivity.teacherData.getEmail(),courseCode,
batchName, courseName, getDateAndTime);
}
}
private void seeAttendanceDetails(final String email,final String
courseCode, final String batchName,final String courseName, final String
date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
seeAttendanceDetails, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
String fullName = data.getString("full_name");
String Email = data.getString("email");
String photo = data.getString("photo");
Toast.makeText(CoursesActivity.this, courseCode,
Toast.LENGTH_LONG).show();
Attendance attendance1 = new Attendance(fullName, Email, photo);
attendanceArrayList.add(attendance1);
}
if (!attendanceArrayList.isEmpty()) {
Intent intent = new Intent(CoursesActivity.this,
ShowAttendanceActivity.class);
Bundle bundle = new Bundle();
bundle.putString("attendanceCourseCode",
courseCode);
bundle.putString("attendanceCourseName",
courseName);
bundle.putString("attendanceBatchName", batchName);
bundle.putSerializable("attendanceList",
attendanceArrayList);
intent.putExtras(bundle);
startActivity(intent);
}
else if (RegistrationActivity.teacherData != null) {
//
seeAttendanceDetails(RegistrationActivity.teacherData.getEmail(),
batchName,courseName, getDateAndTime);
// Toast.makeText(CoursesActivity.this,"No Record
Found",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CoursesActivity.this,
error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("batch", batchName);
params.put("date", date);
params.put("courseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
<br/>
The recycler view activity code
public class ShowAttendanceActivity extends AppCompatActivity implements
ShowAttendanceActivityAdapter.RemoveAttendanceClickListener {
private RecyclerView recyclerView;
private String courseCode,courseName,batchName;
private ArrayList<Attendance> attendanceArrayList = new ArrayList<>();
private TextView
textViewCourseCode,textViewCourseName,textViewBatchName;
private String deleteStudentAttendance =
"https://asuiot.umargulzar.com/Teacher%20API%2
0Files/deleteStudentattendance.php";
int success;
private String TAG_SUCCESS = "success";
private String TAG_MESSAGE = "message";
private String getDateAndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_attendance);
recyclerView = findViewById(R.id.attendance_details_recyclerView);
textViewCourseCode = findViewById(R.id.SA_textView_course_code);
textViewCourseName = findViewById(R.id.SA_textView_course_name);
textViewBatchName = findViewById(R.id.SA_textView_Batch);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
Calendar calendar = Calendar.getInstance();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyy hh:mm:ss a");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
String dateTime = simpleDateFormat.format(calendar.getTime());
this.getDateAndTime = dateTime;
courseCode = (String) getIntent().getStringExtra("attendanceCourseCode");
courseName = (String) getIntent().getStringExtra("attendanceCourseName");
batchName = (String) getIntent().getStringExtra("attendanceBatchName");
attendanceArrayList = (ArrayList<Attendance>) getIntent().getExtras().getSerializable("attendanceList");
textViewCourseCode.setText(courseCode);
textViewCourseName.setText(courseName);
textViewBatchName.setText(batchName);
recyclerView.setAdapter(new ShowAttendanceActivityAdapter(attendanceArrayList,this));
}
#Override
public void onRemoveAttendanceClick(int position,String email) {
// Toast.makeText(ShowAttendanceActivity.this,"The Email of Student:"+email,Toast.LENGTH_LONG).show();
if(MainActivity.teacherData !=null){
deleteStudentAttendance(email,getDateAndTime,courseCode);
}
}
private void deleteStudentAttendance(final String email, final String getDateAndTime,final String courseCode) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, deleteStudentAttendance, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE)+" Plz refresh the page.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", email);
params.put("Date",getDateAndTime);
params.put("CourseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
the recycler view activity adapter
public class ShowAttendanceActivityAdapter extends RecyclerView.Adapter<ShowAttendanceActivityAdapter.AttendanceView> {
private ArrayList<Attendance> attendanceData;
Bitmap bitmap;
private RemoveAttendanceClickListener removeAttendanceClickListener;
public ShowAttendanceActivityAdapter(ArrayList<Attendance> attendanceData,RemoveAttendanceClickListener removeAttendanceClickListener){
this.attendanceData = attendanceData;
this.removeAttendanceClickListener = removeAttendanceClickListener;
}
#NonNull
#Override
public AttendanceView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_attendance_data,parent,false);
return new AttendanceView(view,removeAttendanceClickListener);
}
#Override
public void onBindViewHolder(#NonNull AttendanceView holder, int position) {
Attendance attendance = attendanceData.get(position);
holder.textViewName.setText(attendance.getStudentName());
// holder.textViewEmail.setText(attendance.getStudentEmail());
holder.textViewEmail.setText(attendance.getStudentEmail());
decodeStringToImage(attendance.getStudentPhoto());
holder.imageViewPhoto.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return attendanceData.size();
}
public void decodeStringToImage(String photo) {
// Bitmap bitmap = photo.
byte[] bytes = Base64.decode(photo, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public class AttendanceView extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textViewName, textViewEmail;
ImageView imageViewPhoto;
Button buttonRemoveCourse;
RemoveAttendanceClickListener removeAttendanceClickListener;
public AttendanceView(#NonNull View itemView,RemoveAttendanceClickListener removeAttendanceClickListener) {
super(itemView);
textViewName = itemView.findViewById(R.id.textView_name);
textViewEmail = itemView.findViewById(R.id.textView_Email);
imageViewPhoto = itemView.findViewById(R.id.textView_SA_Photo);
this.removeAttendanceClickListener = removeAttendanceClickListener;
buttonRemoveCourse = itemView.findViewById(R.id.btn_remove_attendance);
buttonRemoveCourse.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_remove_attendance:
removeAttendanceClickListener.onRemoveAttendanceClick(getAdapterPosition(),textViewEmail.getText().toString());
break;
}
}
}
public interface RemoveAttendanceClickListener{
void onRemoveAttendanceClick(int position,String email);
}
}
You are probably getting OutOfMemory exception while converting bytes array in to bitmap if the image sizes are huge.
Add try catch in your decodeStringToImage method where you are converting bitmaps and check the log when you load more than 8 images.
I use Volley in the onCreate of my Activity which gets a string on my server, then I convert this string to an arraylist,checkedContactsAsArrayList, and I pass it over to my custom adapter using sharedpreferences, which does stuff with the arraylist in the listview.
But the custom adapter keeps getting the previous arraylist in sharedpreferences, not the one I've just got from the server. The Volley call is too late or something - I can see in logcat the latest values are put after they are got, if you know what I mean.
For example:
VolleyCall 1 putString: 1,2,3
VolleyCall 2 putString: 4,5,6
VolleyCall 3 putString: 7,8,9
Custom Adapter 1 getString: gets values of the last time app was used
Custom Adapter 2 getString: 1,2,3
Custom Adapter 3 getString: 4,5,6
Any idea how to fix this? I could try doing the Volley call in the getView of my custom adapter but I've read on Stackoverflow that's bad practice.
Here are the relvant parts of my code - I've slimmed it down a bit, as there's a lot of stuff in there irrelevant to this issue.
Here's the code of my activity, ViewContact:
public class ViewContact extends AppCompatActivity implements android.widget.CompoundButton.OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_view_contact);
//selectPhoneContacts is an empty array list that will hold our SelectPhoneContact info
selectPhoneContacts = new ArrayList<SelectPhoneContact>();
listView = (ListView) findViewById(R.id.listviewPhoneContacts);
StringRequest stringRequest = new StringRequest(Request.Method.POST, ViewContact_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//toast the response of ViewContact.php, which has been converted to a
//JSON object by the Php file with JSON encode
Toast.makeText(ViewContact.this, "OnResponse is" + response, Toast.LENGTH_LONG).show();
System.out.println("ViewContact: And the response is " + response);
try {
//checkedContacts is a String
String checkedContacts = responseObject.getString("checkedcontacts");
//convert the checkedContacts string to an arraylist
checkedContactsAsArrayList = new ArrayList<String>(Arrays.asList(checkedcontacts.split(",")));
System.out.println("ViewContact: checkedContactsAsArrayList is " + checkedContactsAsArrayList);
//we want to bring the checkedContactsAsArrayList array list to our SelectPhoneContactAdapter.
// It looks like Shared Preferences
//only works easily with strings so best way to bring the array list in Shared Preferences is with
//Gson.
//Here, we PUT the arraylist into the sharedPreferences
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorcheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.edit();
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = gsoncheckedContactsAsArrayList.toJson(checkedContactsAsArrayList);
editorcheckedContactsAsArrayList.putString("checkedContactsAsArrayList", jsoncheckedContactsAsArrayList);
editorcheckedContactsAsArrayList.commit();
System.out.println("ViewContact: jsoncheckedContactsAsArrayList is " + jsoncheckedContactsAsArrayList);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewContact.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//we are posting review_id into our ViewContact.php file, which
//we get when a row is clicked in populistolistview
//to get matching details
params.put("review_id", review_id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//checkBoxforContact.setChecked(true);
}
//******for the phone contacts in the listview
// Load data in background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
//we want to delete the old selectContacts from the listview when the Activity loads
//because it may need to be updated and we want the user to see the updated listview,
//like if the user adds new names and numbers to their phone contacts.
selectPhoneContacts.clear();
SelectPhoneContact selectContact = new SelectPhoneContact();
selectContact.setName(phoneNameofContact);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectPhoneContactAdapter(selectPhoneContacts, ViewContact.this,0);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onResume() {
super.onResume();
// getPrefs();
ViewContact.LoadContact loadContact = new ViewContact.LoadContact();
loadContact.execute();
Toast.makeText(ViewContact.this, "resuming!", Toast.LENGTH_SHORT).show();
}
}
And my custom adapter, SelectPhoneContactAdapter :
public class SelectPhoneContactAdapter extends BaseAdapter {
//define a list made out of SelectPhoneContacts and call it theContactsList
public List<SelectPhoneContact> theContactsList;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectPhoneContact> arraylist;
Context _c;
ArrayList<String> MatchingContactsAsArrayList;
ArrayList<String> checkedContactsAsArrayList;
ArrayList <String> allNamesofContacts;
String contactToCheck;
//we will run through different logic in this custom adapter based on the activity that is passed to it
private int whichactivity;
String phoneNumberofContact;
String[] phoneNumberofContactStringArray;
String ContactsString;
Intent intent;
public SelectPhoneContactAdapter(final List<SelectPhoneContact> selectPhoneContacts, Context context, int activity) {
theContactsList = selectPhoneContacts;
_c = context;
this.arraylist = new ArrayList<SelectPhoneContact>();
this.arraylist.addAll(theContactsList);
whichactivity = activity;
//we are fetching the array list checkedContactsAsArrayList, created in ViewContact.
//with this we will put a tick in the checkboxes of contacts the review is being shared with
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(_c);
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.getString("checkedContactsAsArrayList", "");
Type type2 = new TypeToken<ArrayList<String>>() {
}.getType();
checkedContactsAsArrayList = gsoncheckedContactsAsArrayList.fromJson(jsoncheckedContactsAsArrayList, type2);
System.out.println("SelectPhoneContactAdapter checkedContactsAsArrayList :" + checkedContactsAsArrayList);
}
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public Object getItem(int i) {
return arraylist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
static class ViewHolder {
//In each cell in the listview show the items you want to have
//Having a ViewHolder caches our ids, instead of having to call and load each one again and again
TextView title, phone;
CheckBox check;
Button invite;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
//this is the SelectPhoneContact object; consists of textboxes, buttons, checkbox
final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);
ViewHolder holder = null;
if (convertView == null) {
//if there is nothing there (if it's null) inflate the view with the layout
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.phone_inflate_listview, null);
holder = new ViewHolder();
//So, for example, title is cast to the name id, in phone_inflate_listview,
//phone is cast to the id called no etc
holder.title = (TextView) convertView.findViewById(R.id.name);
holder.phone = (TextView) convertView.findViewById(R.id.no);
holder.invite = (Button) convertView.findViewById(R.id.btnInvite);
holder.check = (CheckBox) convertView.findViewById(R.id.checkBoxContact);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//in the listview for contacts, set the name
holder.title.setText(data.getName());
//in the listview for contacts, set the number
holder.phone.setText(data.getPhone());
holder.check.setTag(data);
return convertView;
}
}
Call this: loadContact.execute();
After you call .commit();
ViewContact.LoadContact loadContact = new ViewContact.LoadContact();
loadContact.execute();
I have an activity in which I have used Recycle View to show all items as a list. On same activity I have given functionality to add new item. Everything is working fine. Items are adding in my database and its showing in list. I have added pagination on Recycle View it is also working fine. What I want that when user add new item at the same time when new data added to database but it is not updating in list. When user press back and again come on activity after that it is showing in list. I want to add add new item at same time without scroll the list or without go back.
TimelineActivity.java
public class TimelineActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private TimeLineListAdapter listAdapter;
private List<TimeLineItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
btnPost = (Button) findViewById(R.id.btnPost);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
buttonClickEvent();
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, "1");
}
});
}
}, 0, 2000);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
public void buttonClickEvent() {
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isInternetPresent) {
String text = txtStatusBox.getText().toString().trim();
if (!text.isEmpty()) {
if (thumbnail != null) {
String image = getStringImage(thumbnail);
JSONObject student2 = new JSONObject();
try {
student2.put("size", "1000");
student2.put("type", "image/jpeg");
student2.put("data", image);
} catch (JSONException e) {
e.printStackTrace();
}
addStory(text, token, String.valueOf(student2));
} else {
addStory(text, token, "");
}
} else {
Toast.makeText(TimelineActivity.this, "Please add some text or image.", Toast.LENGTH_SHORT).show();
}
} else {
final SweetAlertDialog alert = new SweetAlertDialog(TimelineActivity.this, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
imgImageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
/*fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialogFragment.show(getFragmentManager(), "MyDialogFragment");
//Toast.makeText(TimelineActivity.this, "Floating Button", Toast.LENGTH_SHORT).show();
}
});*/
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
TimeLineListAdapter.java
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
You have to notifiy dataset changed on listview when new feed is added so there are two things you can do :
Create a new TimeLineItem item when new feed is entered and add new item to it like this :
`
item.setStatus("New Status");
item.setProfilePic("New Profile Pic");
item.setTimeStamp("New TimeStamp");
item.setIsLike("True");
item.setTotalLikes("1000");
item.setTotalComment("2");
`
and then use timeLineItems.add(item) to add new item to ArrayList and call adapter.notifyDataSetChanged(); to get it in view .
2. Again create volley request and it will do it automatically but this is slower then above example.
If you have any query please ask .
You have to set this new list to the adapter.
You can create a setDataSet() method in your adapter and call it before notifydatasetchanged
Add below method in adapter
public void setDataSet(List<TimeLineItem> timeLineItems) {
this.timeLineItems = timeLineItems;
}
and call it before notifydatasetChanged like this:
adapter.setDataSet(timeLineItems);
adapter.notifyDataSetChanged();
I need some help to fix this problem. I have a PieChart which is drawn in my android App using some data from a MySQL db. I am using an AsyncTask class implementation which loads the data from the server making an HTTPPostRequest and parsing the JSON response that is returned. The chart comes out fine and is drawn on the screen. The problem comes out when I rotate the device's screen: the Chart behaves abnormally and draws slices again... I don't know why it is doing that, but I read that if you rotate the screen all the methods of the Activity are called again (the onCreate(), onStart() and onResume() methods). Maybe it's because of that??? But I am not sure... Here is how is look like:
Then when I rotate the device:
The data are duplicated! Why? What am I mistaking?
Here is all the code:
public class ComeHaInvestito extends Activity {
/**** PieChartBuilder ****/
/** Colors to be used for the pie slices. */
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN };
/** The main series that will include all the data. */
private CategorySeries mSeries = new CategorySeries("");
/** The main renderer for the main dataset. */
private DefaultRenderer mRenderer = new DefaultRenderer();
/** Edit text field for entering the slice value. */
//private EditText mValue;
/** The chart view that displays the data. */
private GraphicalView mChartView;
private int HowmanyTimes;
#Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
mSeries = (CategorySeries) savedState.getSerializable("current_series");
mRenderer = (DefaultRenderer) savedState.getSerializable("current_renderer");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("current_series", mSeries);
outState.putSerializable("current_renderer", mRenderer);
}
/**** ComeHaInvestito ****/
// String which will store the values of the user
String municipalityName;
String year;
String versedMoney;
// List<Item> ArrayList that will be used to store data from DB
List<Item> MasterAndDetailstatisticsInfoList;
private static final String TAG_COMUNE = "mun_name";
private static final String TAG_ANNO = "year";
private static final String TAG_VERSED_MONEY = "versed_money";
private static final String TAG_SUCCESS = "success";
// POST request information
private static final String URL_ANDROID_APP_LISTENER = "http://xxx.xxx.xxx.xxx/androidApp/AndroidListener.php";
private ProgressDialog pDialog;
// JSONParser instance
JSONParser jParser = new JSONParser();
// JSON data retrieving information
private static final String JSON_STATISTICS_INFOS_LABEL = "statistics_infos";
private static final String JSON_MASTER_LABEL = "master";
private static final String JSON_DETAIL_LABEL = "detail";
private static final String JSON_MASTER_DETAIL_NAME_LABEL = "name";
private static final String JSON_MASTER_DETAIL_VALUE_LABEL ="value";
// statistics info JSON Array which will contain the Master and Detail data that will come from the POST request
JSONArray statisticsInfo = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_come_ha_investito);
Log.d("OnCREATE", "CREO L'ACTIVITY");
// recovering data from previous actitity
Intent iMieiDati = getIntent();
this.municipalityName = iMieiDati.getStringExtra(TAG_COMUNE);
this.year = iMieiDati.getStringExtra(TAG_ANNO);
this.versedMoney = iMieiDati.getStringExtra(TAG_VERSED_MONEY);
// instantiating the needed data structure
MasterAndDetailstatisticsInfoList = new ArrayList<Item>();
mRenderer.setStartAngle(270);
mRenderer.setDisplayValues(true);
new LoadAllMunicipalitiesInvestmentStatisticsThread().execute();
//mRenderer.setZoomButtonsVisible(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pie_chart_builder2, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(ComeHaInvestito.this, "No chart element selected", Toast.LENGTH_SHORT).show();
}
else {
for (int i = 0; i < mSeries.getItemCount(); i++) {
mRenderer.getSeriesRendererAt(i).setHighlighted(i == seriesSelection.getPointIndex());
}
// mChartView.repaint();
Toast.makeText(
ComeHaInvestito.this,
"Chart data point index " + seriesSelection.getPointIndex() + " selected"
+ " point value=" + seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
else {
//mChartView.repaint();
}
}
private void initChart() {
int i=0;
double value=0;
for (Item item : MasterAndDetailstatisticsInfoList) {
if (i == 4) {
break;
}
Log.d("Ciclo ", "NUMERO " + i);
if (item.getViewType() == EntryType.MASTER.ordinal()) {
MasterWithValue master = (MasterWithValue) item;
Log.d("MASTER NAME", master.getMasterName());
Log.d("MASTER VALUE", master.getMasterValue());
try {
value = Double.parseDouble(master.getMasterValue());
}
catch (NumberFormatException e) {
// value is not a decimal
}
mSeries.add(master.getMasterName(), value);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[i%4]);
i++;
mRenderer.addSeriesRenderer(renderer);
Log.d("mSeries", mSeries.toString());
}
}
}
/**** Background Thread ****/
public class LoadAllMunicipalitiesInvestmentStatisticsThread extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ComeHaInvestito.this);
pDialog.setMessage("Caricamento...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("ilMioComune", "Caricamento Statistiche Investimenti");
// building the HTTP POST request
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_COMUNE, municipalityName));
params.add(new BasicNameValuePair(TAG_ANNO, year));
params.add(new BasicNameValuePair(TAG_VERSED_MONEY, versedMoney));
Log.d("params", params.toString());
JSONObject json = jParser.makeHttpRequest(URL_ANDROID_APP_LISTENER, "POST", params);
Log.d("JSON POST statistics investments", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
statisticsInfo = json.getJSONArray(JSON_STATISTICS_INFOS_LABEL);
// foreach Statistics Master Entry
for (int i = 0; i<statisticsInfo.length(); i++) {
JSONObject JSONstatisticsInfo = statisticsInfo.getJSONObject(i);
JSONObject JSONmasterEntry = JSONstatisticsInfo.getJSONObject(JSON_MASTER_LABEL);
String masterEntryName = JSONmasterEntry.getString(JSON_MASTER_DETAIL_NAME_LABEL);
String masterEntryValue = JSONmasterEntry.getString(JSON_MASTER_DETAIL_VALUE_LABEL);
MasterAndDetailstatisticsInfoList.add(new MasterWithValue(masterEntryName, masterEntryValue));
JSONArray JSONdetails = JSONmasterEntry.getJSONArray(JSON_DETAIL_LABEL);
for (int j = 0; j<JSONdetails.length(); j++) {
JSONObject JSONdetailEntry = JSONdetails.getJSONObject(j);
String detailEntryName = JSONdetailEntry.getString(JSON_MASTER_DETAIL_NAME_LABEL);
String detailEntryValue = JSONdetailEntry.getString(JSON_MASTER_DETAIL_VALUE_LABEL);
MasterAndDetailstatisticsInfoList.add(new Detail(detailEntryName, detailEntryValue));
}
}
}
else {
// no statistics infos associated to the selected municipality were found
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
String MasterAndDetails = MasterAndDetailstatisticsInfoList.toString();
Log.d("List", MasterAndDetails);
// Creating the pie chart using the data recovered from the DB
initChart();
}
});
}
}
}
Does anyone have any idea on how to resolve this problem?
Thanks for the attention! Hope fore some help!
You are correct in that onCreate(), onResume(), etc. get called whenever you rotate. Because of this, you are calling new LoadAllMunicipalitiesInvestmentStatisticsThread().execute(); twice essentially.
You should move your data initialization logic to one place, and either load that data from the savedInstanceState, or call the initialize logic if the savedInstanceState returns null.
For example:
change declaration to
private CategorySeries mSeries = null;
in onCreate()
if(savedInstanceState != null)
mSeries = (CategorySeries) savedInstanceState.getSerializable("current_series");
if(mSeries == null)
{
mSeries = new CategorySeries("");
new LoadAllMunicipalitiesInvestmentStatisticsThread().execute(); //this line can be substituted for a new init method, which would contain the thread.execute
}