Question Model-
public class QuestionModel {
private String Id;
private String question;
private String A;
private String B;
private String C;
private String D;
private String answer;
private String link;
private String set;
public QuestionModel(String id, String question, String a, String b, String c, String d, String answer, String set, String link) {
Id = id;
this.question = question;
A = a;
B = b;
C = c;
D = d;
this.answer = answer;
this.set = set;
this.link = link;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getA() {
return A;
}
public void setA(String a) {
A = a;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getC() {
return C;
}
public void setC(String c) {
C = c;
}
public String getD() {
return D;
}
public void setD(String d) {
D = d;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
Question Activity -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
Toolbar toolbar = findViewById(R.id.toolbar);
broadcastReceiver = new ConnectionReceiver();
setSupportActionBar(toolbar);
question = findViewById(R.id.question);
noindicator = findViewById(R.id.no_indicator);
bookmark1btn = findViewById(R.id.bookmark_btn1);
optioncontainer = findViewById(R.id.options_containers);
sharebtn = findViewById(R.id.share_btn);
nextbtn = findViewById(R.id.next_btn);
image =findViewById(R.id.imageView);
preferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
editor=preferences.edit();
gson =new Gson();
setId = getIntent().getStringExtra("setId");
loadingDialog = new Dialog(this);
loadingDialog.setContentView(R.layout.loading);
loadingDialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.round_corner));
loadingDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
loadingDialog.setCancelable(false);
list = new ArrayList<>();getBookmarks();
bookmark1btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (modelmatch()){
bookmarksList.remove(matchedQuestionPosition);
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark_border));
}else {
bookmarksList.add(list.get(position));
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark));
}
}
});
setId = getIntent().getStringExtra("setId");
loadingDialog = new Dialog(this);
loadingDialog.setContentView(R.layout.loading);
loadingDialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.round_corner));
loadingDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
loadingDialog.setCancelable(false);
list = new ArrayList<>();
loadingDialog.show();
myRef.child("SETS").child(setId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String id = dataSnapshot1.getKey();
String question = dataSnapshot1.child("question").getValue().toString();
String a = dataSnapshot1.child("optionA").getValue().toString();
String b = dataSnapshot1.child("optionB").getValue().toString();
String c = dataSnapshot1.child("optionC").getValue().toString();
String d = dataSnapshot1.child("optionD").getValue().toString();
String correctANS = dataSnapshot1.child("correctAns").getValue().toString();
String link = dataSnapshot1.child("imageurl").getValue().toString();
if(!link.equals("https://firebasestorage.googleapis.com/v0/b/bcs-bangla-c2aa0.appspot.com/o/line1.png?alt=media&token=4ff22c6f-edd9-4571-844e-70612d066296"))
{
Picasso.get().load(link).into(image);
}
else
{
Picasso.get().load(https://firebasestorage.googleapis.com/v0/b/bcs-bangla-c2aa0.appspot.com/o/line1.png?alt=media&token=4ff22c6f-edd9-4571-844e-70612d066296).into(image);
}
list.add(new QuestionModel(id,question,a,b,c,d,correctANS,setId,link));
}
if (list.size() > 0){
for (int i = 0; i < 4; i++){
optioncontainer.getChildAt(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer((Button)v);
}
});
}
playAmin(question,0,list.get(position).getQuestion());
nextbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextbtn.setEnabled(false);
nextbtn.setAlpha(0.7f);
enableoption(true);
position++;
if (position == list.size()){
////score activity
if (interstitialAd.isLoaded()){
interstitialAd.show();
return;
}
Intent scoreIntent =new Intent(QuestionActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",score);
scoreIntent.putExtra("total",list.size());
startActivity(scoreIntent);
finish();
return;
}
count = 0;
playAmin(question,0,list.get(position).getQuestion());
}
});
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String body = list.get(position).getQuestion() + "\n (A) " +
list.get(position).getA() + "\n (B) " +
list.get(position).getB() + "\n (C) " +
list.get(position).getC() + "\n (D) " +
list.get(position).getD();
Intent shareaintent = new Intent(Intent.ACTION_SEND);
shareaintent.setType("text/plain");
shareaintent.putExtra(Intent.EXTRA_SUBJECT, "QUIZ CHALLANGE");
shareaintent.putExtra(Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(shareaintent,"share via"));
}
});
}else {
finish();
Toast.makeText(QuestionActivity.this,"no question",Toast.LENGTH_SHORT).show();
}
loadingDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(QuestionActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
finish();
}
});
}
protected void onPause(){
super.onPause();
storebookmarks();
}
private void playAmin (final View view, final int Value, final String data){
for (int i = 0; i < 4; i++){
optioncontainer.getChildAt(i).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FFCFFFD1")));
}
view.animate().alpha(Value).scaleX(Value).scaleY(Value).setDuration(500).setStartDelay(100)
.setInterpolator(new DecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
if (Value == 0 && count < 4){
String option = "";
if (count == 0){
option = list.get(position).getA();
}else if (count == 1){
option = list.get(position).getB();
}else if (count == 2){
option = list.get(position).getC();
}else if (count == 3){
option = list.get(position).getD();
}
playAmin(optioncontainer.getChildAt(count),0,option);
count++;
}
}
#Override
public void onAnimationEnd(Animator animation) {
////Data change
if (Value == 0){
try {
((TextView) view).setText(data);
noindicator.setText(position+1+"/"+list.size());
if (modelmatch()){
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark));
}else {
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark_border));
}
}catch (ClassCastException ex){
((Button) view).setText(data);
}
view.setTag(data);
playAmin(view,1,data);
}else {
enableoption(true);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private void checkAnswer(Button selectedOption){
enableoption(false);
nextbtn.setEnabled(true);
nextbtn.setAlpha(1);
if (selectedOption.getText().toString().equals(list.get(position).getAnswer())){
////correct ans
score++;
selectedOption.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4CAF50")));
//Toast.makeText(QuestionActivity.this,score,Toast.LENGTH_SHORT).show();
}else {
///incorrect ans
selectedOption.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FF0000")));
Button correctOption = (Button) optioncontainer.findViewWithTag(list.get(position).getAnswer());
correctOption.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4CAF50")));
}
}
private void enableoption(boolean enable){
for (int i = 0;i < 4;i++){
optioncontainer.getChildAt(i).setEnabled(enable);
if (enable){
optioncontainer.getChildAt(i).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FFCFFFD1")));
}
}
}
private void getBookmarks(){
String json= preferences.getString(KEY_NAME,"");
Type type = new TypeToken<List<QuestionModel>>(){}.getType();
bookmarksList = gson.fromJson(json, type);
if (bookmarksList == null){
bookmarksList = new ArrayList<>();
}
}
private boolean modelmatch(){
boolean matched = false;
int i = 0;
for (QuestionModel model : bookmarksList){
if (model.getQuestion().equals(list.get(position).getQuestion())
&& model.getAnswer().equals(list.get(position).getAnswer())
&& model.getSet().equals(list.get(position).getSet())){
matched = true;
matchedQuestionPosition = i;
}
i++;
}
return matched;
}
private void storebookmarks(){
String json = gson.toJson(bookmarksList);
editor.putString(KEY_NAME,json);
editor.commit();
}
protected void registoreNetworkBroadcast(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
registerReceiver(broadcastReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregistorNetwork(){
try{
unregisterReceiver(broadcastReceiver);
}catch(IllegalArgumentException e){
e.printStackTrace();
}
}
#Override
protected void onDestroy(){
super.onDestroy();
unregistorNetwork();
}
private void loadAds(){
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getResources().getString(R.string.interstitialAd_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd
.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
interstitialAd.loadAd(new AdRequest.Builder().build());
Intent scoreIntent =new Intent(QuestionActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",score);
scoreIntent.putExtra("total",list.size());
startActivity(scoreIntent);
finish();
return;
}
});
}
}
There are Question Activity of a quiz app. Here I want to show different image from firebase in every question for the quiz app. I have tried to show image.I have added imageurl in QuestionModel and tried to show using picasso library.But it did not worked.In every question same image shown although i have added different links of image(which i have stored in firebase storage and added the link in question in firebase) in firebase but with every question is shows the same image . Please help me to do this.
Related
So I am relatively new to programming, and I have been working on this task app, where I want to save the data such as task name and more, given by the user. I am trying to accomplish this using Room. Now, initially, when I tried to do it, the app would crash since I was doing everything on the main thread probably. So, after a little research, I came to AsyncTask, but that is outdated. Now finally I have come across the Executer. I created a class for it, but I am a little unsure as to how I can implement it in my app. This is what I did :
Entity Class :
#Entity (tableName = "subtasks")
public class SubtaskDetails {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "subtaskName")
private String subtasksName;
#ColumnInfo(name = "priority")
private boolean priHigh;
private boolean priMed;
private boolean priLow;
#ColumnInfo(name = "time")
private boolean timeMore;
private boolean timeMed;
private boolean timeLess;
public SubtaskDetails(String subtasksName, boolean priHigh, boolean priMed, boolean priLow, boolean timeMore, boolean timeMed, boolean timeLess){
this.subtasksName = subtasksName;
this.priHigh = priHigh;
this.priMed = priMed;
this.priLow = priLow;
this.timeMore = timeMore;
this.timeMed = timeMed;
this.timeLess = timeLess;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubtasksName() {
return subtasksName;
}
public void setSubtasksName(String subtasksName) {
this.subtasksName = subtasksName;
}
public boolean isPriHigh() {
return priHigh;
}
public void setPriHigh(boolean priHigh) {
this.priHigh = priHigh;
}
public boolean isPriMed() {
return priMed;
}
public void setPriMed(boolean priMed) {
this.priMed = priMed;
}
public boolean isPriLow() {
return priLow;
}
public void setPriLow(boolean priLow) {
this.priLow = priLow;
}
public boolean isTimeMore() {
return timeMore;
}
public void setTimeMore(boolean timeMore) {
this.timeMore = timeMore;
}
public boolean isTimeMed() {
return timeMed;
}
public void setTimeMed(boolean timeMed) {
this.timeMed = timeMed;
}
public boolean isTimeLess() {
return timeLess;
}
public void setTimeLess(boolean timeLess) {
this.timeLess = timeLess;
}
}
Dao Class:
#Dao
public interface UserDao {
#Query("Select * from subtasks")
List<SubtaskDetails> getSubtaskDetailsList();
#Insert
void insertSubtaskDetails(SubtaskDetails subtaskDetails);
#Update
void updateSubtaskDetails(SubtaskDetails subtaskDetails);
#Delete
void deleteSubtaskDetails(SubtaskDetails subtaskDetails);
}
App Database Class :
#Database(entities = SubtaskDetails.class, exportSchema = false, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static final String DB_NAME = "subtaskdetails_db";
private static AppDatabase instance;
public static synchronized AppDatabase getInstance(Context context){
if (instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME).fallbackToDestructiveMigration().build();
}
return instance;
}
public abstract UserDao subtaskdetailsdao();
}
Executer Class :
public class AppExecutors {
// For Singleton instantiation
private static final Object LOCK = new Object();
private static AppExecutors sInstance;
private final Executor diskIO;
private final Executor mainThread;
private final Executor networkIO;
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
this.diskIO = diskIO;
this.networkIO = networkIO;
this.mainThread = mainThread;
}
public static AppExecutors getInstance() {
if (sInstance == null) {
synchronized (LOCK) {
sInstance = new AppExecutors(Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(3),
new MainThreadExecutor());
}
}
return sInstance;
}
public Executor diskIO() {
return diskIO;
}
public Executor mainThread() {
return mainThread;
}
public Executor networkIO() {
return networkIO;
}
private static class MainThreadExecutor implements Executor {
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
#Override
public void execute(#NonNull Runnable command) {
mainThreadHandler.post(command);
}
}
}
Where I try to implement it : (I have written a comment where I do it)
public class TaskInfo extends AppCompatActivity {
//Declaring variables
EditText etWorkingHours, etWorkingMinutes, etTaskName, etWorkingMins, etWorkinghrs, etSubtaskName;
Button btnNewSubtask;
Button btnSaveTaskName;
Button btnProceed;
ImageView ivLeft, ivRight;
TextView tvBreakTime;
TextView tvTaskName;
int breaktime = 10;
final int ENTER_SUBTASK = 20;
final int EDIT_SUBTASK = 40;
ListView lvSubtasks;
ArrayList<subtask> subtaskList = new ArrayList<>();
ScrollView scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
//Connecting XML to JAVA
etWorkingHours = findViewById(R.id.etWorkingHours);
etWorkingMinutes = findViewById(R.id.etWorkingMinutes);
etTaskName = findViewById(R.id.etTaskName);
btnNewSubtask = findViewById(R.id.btnNewSubtask);
ivLeft = findViewById(R.id.ivLeft);
ivRight = findViewById(R.id.ivRight);
tvBreakTime = findViewById(R.id.tvBreakTime);
etWorkinghrs = findViewById(R.id.etWorkingHrs);
etWorkingMins = findViewById(R.id.etWorkingMins);
lvSubtasks = findViewById(R.id.lvSubtasks);
scrollView = findViewById(R.id.scrollView);
btnSaveTaskName = findViewById(R.id.btnSaveTask);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
// Code for the left right arrows along with break duration
ivRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (breaktime >= 10 && breaktime < 60)
{breaktime += 5;
String time = breaktime + "";
tvBreakTime.setText(time);}
else
{
String time = breaktime + "";
tvBreakTime.setText(time);
}
}
});
ivLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (breaktime > 10 && breaktime <= 60)
{
breaktime -= 5;
String time = breaktime + "";
tvBreakTime.setText(time);}
else
{
String time = breaktime + "";
tvBreakTime.setText(time);
}
}
});
btnNewSubtask.setEnabled(false);
btnSaveTaskName.setEnabled(false);
//save button enabler when task name is written
etTaskName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
btnSaveTaskName.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
//Applying the max min thing for which the class InputFilterMinMax is defined
etWorkingHours.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etWorkingMinutes.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
etWorkinghrs.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etWorkingMins.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
}
// This is where I try to implement the executer :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_SUBTASK)
{
if (resultCode == RESULT_OK)
{
SubtaskAdapter adapter = new SubtaskAdapter(this, subtaskList);
assert data != null;
String subtaskName = data.getStringExtra("subtaskName");
boolean priHigh = data.getBooleanExtra("priHigh", false);
boolean priMed = data.getBooleanExtra("priMed", false);
boolean priLow = data.getBooleanExtra("priLow", false);
boolean timeMore = data.getBooleanExtra("timeMore", false);
boolean timeMed = data.getBooleanExtra("timeMed", false);
boolean timeLess = data.getBooleanExtra("timeLess", false);
AppDatabase appDb = AppDatabase.getInstance(this);
AppExecutors.getInstance().diskIO().execute(new Runnable() {
#Override
public void run() {
SubtaskDetails subtaskDetails = new SubtaskDetails(subtaskName,priHigh, priMed, priLow, timeMore, timeMed, timeLess);
appDb.subtaskdetailsdao().insertSubtaskDetails(subtaskDetails);
}
});
lvSubtasks.setAdapter(adapter);
subtask subtask = new subtask(subtaskName, priHigh, priMed, priLow, timeMore, timeMed, timeLess);
subtaskList.add(subtask);
adapter.addANewSubTask(subtask);
}
}
}
// Menu (action bar) code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case (R.id.settings):
startActivity(new Intent(this, SettingsActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
//Class to make max and min value on the edit text of hours and minutes, so that they cant enter anything more than 24 hours, and 59 minutes
static class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
}
EDIT :
I implemented the code, but I am facing a few issues in the viewmodel class. For eg, the parameter in repository.insertSubtaskDetails(userDao); is userDao, but it actually it requires of type subtaskDetails.. some errors in the todo part as well. this is the code:
package com.example.taskmasterv3;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import java.util.List;
public class ViewModel extends AndroidViewModel {
private Repository repository;
private List<SubtaskDetails> subtaskDetails;
public ViewModel(#NonNull Application application) {
super(application);
repository = new Repository(application);
subtaskDetails = repository.getSubtaskDetails();
}
public void insert(UserDao userDao) {
repository.insertSubtaskDetails(userDao);
}
public void delete(Todo todo) {
repository.deleteSubtaskDetails(userDao);
}
}
First make a Repository class and make an instance of your DAO
public class Repository {
private UserDAO userDAO;
private List<SubtaskDetails> subtaskDetails;
private Executor executor = Executors.newSingleThreadExecutor();
public Repository(Application application){
AppDatabase appDatabase = AppDatabase.getInstance(application);
userDAO = appDatabase.userDAO();
subtaskDetails = userDAO.getSubtaskDetailsList();
}
Then wrap it around your executor
public void insertSubtaskDetails(SubtaskDetails subtaskDetails){
executor.execute(new Runnable() {
#Override
public void run() {
userDAO.insertSubtaskDetails(subtaskDetails);
}
});
}// For inserting
public void deleteSubtaskDetails(SubtaskDetails subtaskDetails){
executor.execute(new Runnable() {
#Override
public void run() {
userDAO.deleteSubtaskDetails(subtaskDetails);
}
});
}// for deleting
Basically just wrap your DAO queries around the executor.
i am scanning devices from a bluetooth and getting their data from their advertisement,so one of the device gives the data of other devices which is not in ranged from the mobile device,so i specifically filter the data of that device which i wanted to show in recycler view in automatically updating the rssi values.
let's say,
a device A which gives the data of 3 devices B,C,D containing their rssi values continuously,so what i want to show the list of device B,C,D with their rssi values which is changing continuously.
What i have done until now is scan that device "A",and extract the data of B and shown in recyclerview,but when another device i.e C's data comes in the old device i.e B got vanished and so on.
what i want is continuously changing data of B,C,D.
Adapter Class:-
public class ReapeaterDeviceAdapter extends RecyclerView.Adapter<ReapeaterDeviceAdapter.CryptoViewHolder> {
private ArrayList<RepeaterModel> data = new ArrayList<>();;
private Context mCtx;
public class CryptoViewHolder extends RecyclerView.ViewHolder {
private TextView mName, mPrice;
public CryptoViewHolder(View itemView) {
super(itemView);
mName = itemView.findViewById(R.id.txtName);
mPrice = itemView.findViewById(R.id.txtPrice);
}
}
public ReapeaterDeviceAdapter(Context ctx,ArrayList<RepeaterModel> data) {
this.mCtx = ctx;
this.data = data;
}
#Override
public CryptoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.repeater_dev_data,parent, false);
return new CryptoViewHolder(itemView);
}
#Override
public void onBindViewHolder(CryptoViewHolder holder, int position) {
System.out.println("onBinder");
holder.mName.setText(data.get(position).macdev);
holder.mPrice.setText(String.valueOf(data.get(position).rssi));
}
#Override
public void onBindViewHolder(CryptoViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
//System.out.println("onbinder");
super.onBindViewHolder(holder, position, payloads);
} else {
Bundle o = (Bundle) payloads.get(0);
//System.out.println("in keyset");
for (String key : o.keySet()) {
if (key.equals("price")) {
holder.mName.setText(data.get(position).macdev);
holder.mPrice.setText(String.valueOf(data.get(position).rssi));
//holder.mPrice.setTextColor(Color.GREEN);
//this.notifyItemChanged(position);
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public ArrayList<RepeaterModel> getData() {
return data;
}
public void setData(ArrayList<RepeaterModel> newData) {
MyDiffUtilCallBack diffCallBack = new MyDiffUtilCallBack(newData, this.data);
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallBack);
//this.setData(newData);
// this.data=newData;
this.data.clear();
// this.data = newData;
this.data.addAll(newData);
diffResult.dispatchUpdatesTo(this);
//this.notifyItemRangeChanged(0, this.getItemCount());
//this.notifyDataSetChanged();
//System.out.println("Here");
}
}
Model Class:-
public String macdev;
public int rssi ;
public int imageid;
public RepeaterModel(String macdev, int rssi, int imageid) {
this.macdev = macdev;
this.rssi = rssi;
this.imageid = imageid;
}
public String getMacdev() {
return macdev;
}
public void setMacdev(String macdev) {
this.macdev = macdev;
}
public int getRssi() {
return rssi;
}
public void setRssi(int rssi) {
this.rssi = rssi;
}
public int getImageid() {
return imageid;
}
public void setImageid(int imageid) {
this.imageid = imageid;
}
#Override
public boolean equals(Object o) {
System.out.println("in equals");
if (this == o) return true;
if (!(o instanceof RepeaterModel)) return false;
RepeaterModel that = (RepeaterModel) o;
return getRssi() == that.getRssi() &&
getImageid() == that.getImageid() &&
getMacdev().equals(that.getMacdev());
}
#Override
public int hashCode() {
return Objects.hash(getMacdev(), getRssi(), getImageid());
}
/*#Override
public int hashCode() {
int result = Integer.valueOf(rssi);
// result = result + (imageid != 0 ? imageid.hashCode() : 0);
result = result + rssi.hashCode();
System.out.println("hash");
return result;
}*/
}
Diffutilcallback :-
ArrayList<RepeaterModel> newList;
ArrayList<RepeaterModel> oldList;
public MyDiffUtilCallBack(ArrayList<RepeaterModel> newList, ArrayList<RepeaterModel> oldList) {
this.newList = newList;
this.oldList = oldList;
}
#Override
public int getOldListSize() {
return oldList != null ? oldList.size() : 0;
}
#Override
public int getNewListSize() {
return newList != null ? newList.size() : 0;
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
if(newList.get(newItemPosition).getMacdev().equals(oldList.get(oldItemPosition).getMacdev()))
{
// Log.d("itemsame","in same");
return true;
}
else {
// Log.d("itemsame", "not same");
}
return false;
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition)
{
//System.out.println("in content same");
final RepeaterModel oldRepeater = oldList.get(oldItemPosition);
final RepeaterModel newRepeater = newList.get(newItemPosition);
if(oldRepeater.getRssi()!=(newRepeater.getRssi()))
{
//Log.d("item contenets","content different");
return false;
}
//Log.d("item contenets","content same");
return true;
}
#Nullable
#Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
RepeaterModel newModel = newList.get(newItemPosition);
RepeaterModel oldModel = oldList.get(oldItemPosition);
//System.out.println("getchange");
Bundle diff = new Bundle();
//if (newModel.getMacdev().equals(oldModel.getMacdev()))
//{
//System.out.println("getchange");
if (newModel.getRssi()!=(oldModel.getRssi())) {
diff.putInt("price", newModel.getRssi());
}
if (diff.size() == 0) {
return null;
}
// }
return diff;
//return super.getChangePayload(oldItemPosition, newItemPosition);
}
}```
Activity Class:-
public class RepeaterAdvertise extends AppCompatActivity {
private static BluetoothAdapter mBluetoothAdapter;
private static BluetoothLeScanner mLEScanner;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private static boolean mScanning;
private static Handler mHandler;
private static final long SCAN_TIMEOUT = 20000;
public DevData data;
public Button cc;
//List<BluetoothDevice> mBluetoothDevice;
RecyclerView recyclerView;
ReapeaterDeviceAdapter reapeaterDeviceAdapter;
ArrayList<RepeaterModel> modelArrayList;// = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repeater_advertise);
modelArrayList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.devdata);
//dummyData();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
reapeaterDeviceAdapter = new ReapeaterDeviceAdapter(RepeaterAdvertise.this, modelArrayList);
recyclerView.setAdapter(reapeaterDeviceAdapter);
mHandler = new Handler();
final Intent intent = getIntent();
data = (DevData) intent.getSerializableExtra(SINGLE_DEV_DATA);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false,data.getMac_address());
}
#Override
protected void onResume() {
super.onResume();
scanLeDevice(true,data.getMac_address());
}
private void scanLeDevice(final boolean enable,String mac) {
if (enable) { // enable set to start scanning
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(mScanning) {
mScanning = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
invalidateOptionsMenu();
}
}
}, SCAN_TIMEOUT);
mScanning = true;
UUID[] motorServiceArray = {PSoCBleRobotService.getMotorServiceUUID()};
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//noinspection deprecation
mBluetoothAdapter.startLeScan(motorServiceArray, mLeScanCallback);
} else { // New BLE scanning introduced in LOLLIPOP
ScanSettings settings;
List<ScanFilter> filters;
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<>();
//ScanFilter filter = new ScanFilter.Builder().setServiceUuid(PUuid).build();
//ScanFilter filter = new ScanFilter.Builder().setManufacturerData(89,new byte[] {}).build();
ScanFilter filter = new ScanFilter.Builder().setDeviceAddress(mac).build();
filters.add(filter);
if(mLEScanner==null)
{
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else { // enable set to stop scanning
if(mScanning) {
mScanning = false;
if (Build.VERSION.SDK_INT < 21) {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
invalidateOptionsMenu();
}
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run()
{
byte[] haha = scanRecord;
/* if(!mBluetoothDevice.contains(device))
{
//only add new devices
mBluetoothDevice.add(device);
mBleName.add(device.getName());
mBleArrayAdapter.notifyDataSetChanged(); // Update the list on the screen
}*/
}
});
}
};
public static String SbytesToHex(SparseArray<byte[]> bytes) {
StringBuilder builder = new StringBuilder();
byte[] dd = bytes.valueAt(0);
for (byte b: dd)
{
builder.append(String.format("%02x", b));
}
//System.out.println( dd.length);
return builder.toString();
}
public final ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
ScanRecord scanRecord = result.getScanRecord();
// mBluetoothDevice.add(result.getDevice());
SparseArray<byte[]> dataw = scanRecord.getManufacturerSpecificData();
if (dataw.size() > 0) {
//populate_devData(SbytesToHex(dataw));
String data = SbytesToHex(dataw);
ArrayList<RepeaterModel> repeaterModels= new ArrayList<>();
int rssi = Integer.valueOf(data.substring(12, 14), 16) - 256;
repeaterModels.add(new RepeaterModel(data.substring(0, 12), rssi, 1));
insert(repeaterModels);
} else if (false) {
//alertDialog.dismiss();
final Intent intent = new Intent(RepeaterAdvertise.this, ConfigurationView.class);
intent.putExtra(EXTRAS_BLE_ADDRESS, data.getMac_address());
intent.putExtra(EXTRAS_BLE_NAME, data.getName());
intent.putExtra(SINGLE_DEV_DATA, data.getDev_data());
scanLeDevice(false, data.getMac_address());
//mconfig=false;
startActivity(intent);
}
}
};
public void insert(ArrayList<RepeaterModel> rr)
{
modelArrayList.addAll(rr);
reapeaterDeviceAdapter.setData(rr);
}
}
add this line in insert function reapeaterDeviceAdapter.notifyDataSetChanged();
public void insert(ArrayList<RepeaterModel> rr){
modelArrayList.addAll(rr);
reapeaterDeviceAdapter.setData(rr);
reapeaterDeviceAdapter.notifyDataSetChanged();
}
The above image is a simple design that I want to develop.
I have four type of different data with different view type like the below image enter image description here. but that is not a problem. problem is the data will come from different API with lazy loading like when user scroll the list from recycle view it will grab the data from the server. My question is how to combine them in a single adapter because I need to use lazy loading .so I can't load whole data at a time so I need to call the different type of API like goal-list API, appraisal API, post API etc. When user scroll. anyone can give me an idea with example. How can I handle that? Also when user will scroll it will call another api likeCount and comment count also. Currently, In my, I am calling single API and show that in the single recycle view. Currently, I am using android architecture component LiveData
Fragment :
public class NewsFeedFragment extends FcaFragment {
private View view;
private RecyclerView postRecyclerView;
private PostsAdapter postsAdapter;
private List<Post> posts;
private TimelineViewModel timelineViewModel;
private ImageView addPostView;
private View addPostPanel;
private long lastApiCallTime;
private SwipyRefreshLayout swipeRefresh;
private long lastScroolItemInPost= 0;
public NewsFeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(lastScroolItemInPost < 1) {
initViewModel(1 , 0 , true);
lastScroolItemInPost = 1;
}else {
initViewModel(((int) lastScroolItemInPost + 5), lastScroolItemInPost , true);
lastScroolItemInPost += 5;
}
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ownerActivity);
view = inflater.inflate(R.layout.fragment_news_feed, container, false);
postRecyclerView = (RecyclerView) view.findViewById(R.id.postRecyclerView);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView postRecyclerView, int dx, int dy) {
super.onScrolled(postRecyclerView, dx, dy);
int lastVisiableItemInPostList = linearLayoutManager.findLastVisibleItemPosition();
if(lastScroolItemInPost < lastVisiableItemInPostList)
{
if(lastScroolItemInPost == 1)
{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false);
lastScroolItemInPost += 2;
}else{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false );
lastScroolItemInPost += 2;
}
}
}
});
posts = new ArrayList<>();
postRecyclerView.setLayoutManager(linearLayoutManager);
postsAdapter = new PostsAdapter(ownerActivity,posts,timelineViewModel);
postRecyclerView.setAdapter(postsAdapter);
swipeRefresh = (SwipyRefreshLayout) view.findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if(direction == SwipyRefreshLayoutDirection.TOP){
timelineViewModel.fetchPosts2();
}
if(direction == SwipyRefreshLayoutDirection.BOTTOM){
timelineViewModel.fetchPosts();
}
}
});
return view;
}
private void initViewModel(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment) {
TimelineViewModel.Factory factory = new TimelineViewModel.Factory(UserPreferences.getToken(ownerActivity), TaskUtils.getMySelfContact(ownerActivity));
timelineViewModel = ViewModelProviders.of(this,factory).get(TimelineViewModel.class);
timelineViewModel.getPostList().observe(this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
postsAdapter.setPostList(posts);
swipeRefresh.setRefreshing(false);
}
});
timelineViewModel.getPostDeleted().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(#Nullable Boolean aBoolean) {
if(aBoolean){
postsAdapter.setPostList(Post.getAll());
}
}
});
timelineViewModel.init( lastVisiableItemInPostList , lastScroolItemInPost ,isFirstTimeOpenFeedFragment);
}
}
ViewModel :
public class TimelineViewModel extends FCViewModel implements PostDetailsDownloadManager.PostDetailDownloadedListener,OnContactReceivedListner{
public TimelineViewModel(String token,Contact user){
super(token);
this.user = user;
post = new MutableLiveData<>();
postDeleted = new MutableLiveData<>();
}
public void init(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment){
repository =
//postDetailsDownloadManager = ServiceLocator.getServiceLocator().postDetailsDownloadManager;
likePostDownloadManager = ServiceLocator.getServiceLocator().likePostDownloadManager;
likePostDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<LikePostTouple>() {
#Override
public void onDataDownloaded(List<LikePostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(LikePostTouple dataTouple) {
}
});
postDetailDownloadManager = ServiceLocator.getServiceLocator().postDetailDownloadManager;
postDetailDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<PostTouple>() {
#Override
public void onDataDownloaded(List<PostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(PostTouple dataTouple) {
}
});
post.setValue(Post.getAll());
if(isFirstTimeOpenFeedFragment)
{
fetchPosts2();
}
try {
if(Post.getAll().size() > 0)
{
List<Post> tempPosts = Post.getAll();
List<Post> passList = tempPosts.subList( (int) lastScroolItemInPost ,lastVisiableItemInPostList);
fetchLikesOfPosts(passList);
}else{
fetchLikesOfPosts(Post.getAll());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Testing Injecting", repository.toString());
}
public LiveData<List<Post>> getPostList() {
return post;
}
public MutableLiveData<Boolean> getPostDeleted() {
return postDeleted;
}
boolean isContactFetched = false;
public void fetchPosts(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",1);
requestData.put("cpid",Post.getLastPid());
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
private boolean isDataLoading = false;
public void fetchPosts2(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",2);
requestData.put("cpid", Post.getFirstPid()); // cpid means cursor pid
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
public boolean isDataLoading() {
return isDataLoading;
}
private void fetchContacts() {
contactRepository.getData(new Repository.DataFetchedListener<List<Contact>>() {
#Override
public void onDataFetched(List<Contact> data) {
if(data.size()>0 && !isContactFetched) {
fetchPosts2();
isContactFetched = true;
}
}
},null);
}
#NonNull
private PostTouple getPostToubleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new PostTouple(postJson,post.getPid());
}
#NonNull
private LikePostTouple getLkePostToupleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new LikePostTouple(postJson,post.getPid());
}
public void giveLike(String token, final long pid){
Map<String,Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",Long.toString(pid));
likeRepository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
Log.d("Like post", data.toString());
Post post = getPostById(pid);
post.setLikes(data.getLikes());
post.setComments(data.getComments());
TimelineViewModel.this.post.setValue(TimelineViewModel.this.post.getValue());
fetchLikesOfLikedPost(data);
}
},requestData);
}
private void fetchLikesOfLikedPost(Post data) {
try {
likePostDownloadManager.addItemInQueue(getLkePostToupleFromPost(data));
likePostDownloadManager.startDownload();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Post getPostById(long pid){
List<Post> posts = post.getValue();
for(Post post : posts){
if(post.getPid()==pid){
return post;
}
}
return null;
}
public Contact getSenderContactFromComment(Post post) {
if(post.getPqrc().equals(user.getUserId())){
return user;
}
Contact contact = Contact.getByUserId(post.getPqrc());
return contact;
}
public String getDescriptionForType5(Post post,String message){
try {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null) {
String qrc = JSonUtils.qrcFromCntOfPostDetails(postDetail.getContent());
int sid = JSonUtils.skillidFromCntOfPostDetails(postDetail.getContent());
if (qrc == null || sid == 0) {
return "";
}
SkillDb skill = SkillDb.getBySId(Integer.toString(sid));
Contact contact = getPosterContact(post.getPqrc());
return contact.getName() + " " + message + " " + skill.getSkillName() + ".";
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getDescriptionForPost(Post post, String message){
if(post.getCtype()==1){
return post.getDescr();
}
if(post.getCtype() == 2){
String postDetail = getContent(post);
if (postDetail != null) return Html.fromHtml(""+postDetail+"").toString();
}
if(post.getCtype()==5){
return getDescriptionForType5(post, message);
}
return "";
}
#Nullable
public String getContent(Post post) {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null){
return postDetail.getContent();
}
return null;
}
public Contact getPosterContact(String qrc){
try {
String userqrc = user.getUserId();
if (userqrc.equals(qrc)) {
return user;
}
}catch (Exception e){
e.printStackTrace();
}
try {
return Contact.getByUserId(qrc);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void fetchUrlPreview(String url, final UrlMetaDataFetchListener metaDataFetchListener){
String modifiedUrl = !url.contains("http://")&&!url.contains("https://")? "http://"+url : url;
TextCrawler textCrawler = new TextCrawler();
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
#Override
public void onPre() {
}
#Override
public void onPos(SourceContent sourceContent, boolean b) {
String imageUrl = sourceContent.getImages().isEmpty()? "" : sourceContent.getImages().get(0);
metaDataFetchListener.onMetaDataFetched(sourceContent.getTitle(),sourceContent.getDescription(), imageUrl);
}
};
textCrawler.makePreview(linkPreviewCallback, modifiedUrl,1);
}
public interface UrlMetaDataFetchListener{
void onMetaDataFetched(String title, String description, String imageUrl);
}
#Override
public void onPostDownloaded(PostTouple postTouple) {
this.post.setValue(Post.getAll());
}
#Override
public void onContactsReceived() {
fetchPosts();
}
public void deletePost(long pid) {
Map<String, Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",pid);
repository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
postDeleted.setValue(data!=null);
}
},requestData);
}
public boolean isMyPost(Post post){
return user.getUserId().equals(post.getPqrc());
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private String token;
private Contact user;
public Factory(String token,Contact user) {
this.token = token;
this.user = user;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new TimelineViewModel(token,user);
}
}
}
Adapter :
public class PostsAdapter extends RecyclerView.Adapter {
private Context context;
private List<Post> postList;
private int[] badges = {R.drawable.badge1, R.drawable.badge2, R.drawable.badge3};
private List<Integer> randomNumbers = Utils.getRandomNumberList(2,true);
private ArrayDeque<Integer> randomQueue = new ArrayDeque<>(randomNumbers);
private static Map<Long,URLPreview> urlPreviewMap = new HashMap<>();
private TimelineViewModel timelineViewModel;
public PostsAdapter(Context context, List<Post> postList, TimelineViewModel timelineViewModel){
super();
this.context = context;
this.postList = postList;
this.timelineViewModel = timelineViewModel;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.post_item_layout, null);
PostViewHolder postViewHolder = new PostViewHolder(view);
postViewHolder.setIsRecyclable(false);
return postViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Post post = postList.get(position);
final PostViewHolder postViewHolder = (PostViewHolder) holder;
final String postDetail = timelineViewModel.getDescriptionForPost(post,context.getResources().getString(R.string.postType5message));
setPostDescription(post, postViewHolder, postDetail);
handlePreviewVisibility(post, postViewHolder);
postViewHolder.setLikes(""+post.getLikes()+" Likes");
postViewHolder.setCommentCount("" + post.getComments() + " Comments");
postViewHolder.setSupDescription("Posted By System");
int randomNumber = getRandomNumber();
postViewHolder.setBadgeIcon(badges[randomNumber]);
setPostLikedIndicator(post, postViewHolder);
postViewHolder.getLikeButtonWrapper().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveLikeToPost(post);
if(post.getIsLiked() == 0) {
post.setLikes(post.getLikes() + 1);
postViewHolder.setLikes("" + post.getLikes() + " Likes");
post.setIsLiked(1);
setPostLikedIndicator(post, postViewHolder);
}
}
});
postViewHolder.getCommentPanel().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommentPostFragment fragment = CommentPostFragment.GetInstance(post.getPid());
ViewUtils.launchFragmentKeepingInBackStack(context,fragment);
}
});
Contact contact = timelineViewModel.getPosterContact(post.getPqrc());
if(contact!=null && TaskUtils.isNotEmpty(contact.getImageToken())){
Utils.setImageToImageView(postViewHolder.getPosterImage(),timelineViewModel.getToken(),contact.getImageToken());
postViewHolder.getPosterNameTextView().setText(contact.getName());
}
postViewHolder.getPostingDate().setText(Utils.getDateFromMilliseconds(post.getdC()));
if(post.getCtype() != 3)
{
postViewHolder.contentImage.setVisibility(View.GONE);
postViewHolder.fullScreenIndicatorIcon.setVisibility(View.GONE);
}
if(post.getCtype() == 3){
setContentOfType3(post, postViewHolder);
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
PostViewHolder viewHolder = (PostViewHolder) holder;
viewHolder.pTitle.setText("");
viewHolder.pDescription.setText("");
viewHolder.pImage.setImageDrawable(null);
}
private void handlePreviewVisibility(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()==2){
postViewHolder.preview.setVisibility(View.VISIBLE);
}else{
postViewHolder.preview.setVisibility(View.GONE);
}
}
private void handleShowingOptionsIcon(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()!=5 && timelineViewModel.isMyPost(post)){
postViewHolder.options.setVisibility(View.VISIBLE);
}else{
postViewHolder.options.setVisibility(View.GONE);
}
}
private void giveLikeToPost(Post post) {
post.setLikes(post.getLikes()+1);
post.setIsLiked(1);
//notifyDataSetChanged();
timelineViewModel.giveLike(UserPreferences.getToken(context),post.getPid());
}
private void setPostLikedIndicator(Post post, PostViewHolder postViewHolder) {
if(post.getIsLiked()==1) {
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_red, null));
}else{
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_filled, null));
}
}
private void setPostDescription(final Post post, final PostViewHolder postViewHolder, final String postDetail) {
if(post.getCtype()==2){
String postDescription = "<p>"+ post.getDescr()+"</p>";
postViewHolder.description.setText( Html.fromHtml(postDescription +""+postDetail+"") );
postViewHolder.descriptionContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = !postDetail.contains("http://")&&!postDetail.contains("https://")? "http://"+postDetail : postDetail;
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW,uri));
}
});
URLPreview urlPreview = null;
if((urlPreview=urlPreviewMap.get(post.getPid()))==null) {
timelineViewModel.fetchUrlPreview(postDetail, new TimelineViewModel.UrlMetaDataFetchListener() {
#Override
public void onMetaDataFetched(String title, String description, String imageUrl) {
showURLPreview(title, description, imageUrl, postViewHolder);
urlPreviewMap.put(post.getPid(),new URLPreview(title,description,imageUrl));
}
});
}else {
showURLPreview(urlPreview.getTitle(),urlPreview.getDescription(),urlPreview.getImageUrl(),postViewHolder);
}
}else if(post.getCtype() == 3)
{
String postDescription = post.getDescr();
postViewHolder.description.setText(postDescription);
}
else {
postViewHolder.setDescription(postDetail);
}
}
private void initImageClickListener(final ImageView imageView, final String pictureLink) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> pictureLinks = new ArrayList<String>();
pictureLinks.add(pictureLink);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
ImagePagerFragment imagePagerFragment = ImagePagerFragment.newInstance(pictureLinks, 0, screenLocation, imageView.getWidth(), imageView.getHeight());
ViewUtils.launchPopUpFragmentUpdated(context, imagePagerFragment);
}
});
}
private void showURLPreview(String title, String description, String imageUrl, PostViewHolder postViewHolder) {
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(!TaskUtils.isEmpty(imageUrl)) {
Picasso.with(context)
.load(imageUrl)
.into(postViewHolder.pImage);
}
view.findViewById(R.id.description);
postViewHolder.pTitle.setText(title);
postViewHolder.pDescription.setText(description);
}
#Override
public int getItemCount() {
return postList.size();
}
private int getRandomNumber(){
if(!randomQueue.isEmpty()){
return randomQueue.poll();
}
randomQueue = new ArrayDeque<>(randomNumbers);
return randomQueue.poll();
}
public void setPostList(List<Post> postList) {
this.postList = postList;
notifyDataSetChanged();
Log.d("Data rec", postList.size()+"");
}
class PostViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener {
}
public void setLikes(String likes) {
this.likes.setText(likes);
}
public void setCommentCount(String commentCount)
{
this.commentCount.setText(commentCount);
}
public void setDescription(String description){
this.description.setText(description);
}
public void setSupDescription(String subDescription){
this.supDescription.setText(subDescription);
}
public void setBadgeIcon(int resID){
Utils.setImageViewFromResource(badgeIcon,resID);
}
public ImageView getLikeButton() {
return likeButton;
}
public RelativeLayout getLikeButtonWrapper()
{
return likeButtonWrapper;
}
public ImageView getCommentButton() {
return commentButton;
}
public ImageView getPosterImage() {
return posterImage;
}
public TextView getPosterNameTextView() {
return posterNameTextView;
}
public TextView getPostingDate() {
return postingDate;
}
public RelativeLayout getCommentPanel() {
return commentPanel;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
timelineViewModel.deletePost(postList.get(getAdapterPosition()).getPid());
return false;
}
}
}
I have an activity named EfortActivity which contains 3 EditText, a Spinner, a RadioGroup and a Button - saveButton. My goal is to add data dynamically in a ListView (the listView is implemented in another activity called HistoryActivity).
The problem is that when I click on the saveButton my app crash.
Here is the code in EfortActivity:
public class EfortMonitorizareActivity extends AppCompatActivity {
RadioGroup radioGroupDaNu;
Spinner spinnerTip;
EditText editTextDurata;
EditText editTextInainte;
EditText editTextDupa;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efort_monitorizare);
intent = getIntent();
initializareComponente();
}
private void initializareComponente() {
radioGroupDaNu = (RadioGroup) findViewById(R.id.rg_activitateDANU);
spinnerTip = (Spinner) findViewById(R.id.spin_tip_efort);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.TipEfort, R.layout.support_simple_spinner_dropdown_item);
spinnerTip.setAdapter(adapter);
editTextDurata = (EditText) findViewById(R.id.edt_durataAnt_efort);
editTextInainte = (EditText) findViewById(R.id.edt_greuteInainteAnt_efort);
editTextDupa = (EditText) findViewById(R.id.edt_greutateDupaAnt_efort);
Button btn_inregistrareDate = (Button) findViewById(R.id.btn_adaugaDate_efort);
btn_inregistrareDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validare()) {
Efort efort = createPlayerFromComponents();
if (efort != null) {
intent.putExtra(Constants.ADD_EFORT_KEY,efort);
setResult(RESULT_OK,intent);
finish();
}
}
}
});
}
private Efort createPlayerFromComponents() {
RadioButton checkDaNu = (RadioButton) findViewById(radioGroupDaNu.getCheckedRadioButtonId());
String radioDaNu = checkDaNu.getText().toString();
String tip = spinnerTip.getSelectedItem().toString();
Integer durata = Integer.parseInt(editTextDurata.getText().toString());
Integer inainte = Integer.parseInt(editTextInainte.getText().toString());
Integer dupa = Integer.parseInt(editTextDupa.getText().toString());
return new Efort(radioDaNu, tip, durata, inainte, dupa);
}
private boolean validare() {
RadioButton nu = (RadioButton) findViewById(R.id.button_nu_efort);
if (editTextDurata.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
}
if (editTextInainte.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
}
if (editTextDupa.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
} }
Here is the code for HistoryActivity:
public class IstoricActivity extends AppCompatActivity {
ListView lvEfort;
List<String> listaEfort = new ArrayList<>();
Button deconectare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_istoric);
deconectare=(Button)findViewById(R.id.btn_deconectareIstoric);
deconectare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
//initializare componente
lvEfort = (ListView) findViewById(R.id.lw_listaEfort);
Efort efortDefault = new Efort("Da", "Tennis", 40, 55, 53);
listaEfort.add(efortDefault.toString());
//declarare + initializare adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listaEfort);
lvEfort.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
And the class Efort:
public class Efort implements Parcelable {
private String radioDaNu;
private String tip;
private Integer durata;
private Integer inainte;
private Integer dupa;
public Efort(String radioDaNu, String tip, Integer durata, Integer inainte, Integer dupa) {
this.radioDaNu = radioDaNu;
this.tip = tip;
this.durata = durata;
this.inainte = inainte;
this.dupa = dupa;
}
public String getRadioDaNu() {
return radioDaNu;
}
public void setRadioDaNu(String radioDaNu) {
this.radioDaNu = radioDaNu;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public Integer getDurata() {
return durata;
}
public void setDurata(Integer durata) {
this.durata = durata;
}
public Integer getInainte() {
return inainte;
}
public void setInainte(Integer inainte) {
this.inainte = inainte;
}
public Integer getDupa() {
return dupa;
}
public void setDupa(Integer dupa) {
this.dupa = dupa;
}
#Override
public String toString() {
return "Efort{" +
// ", datePicker=" + datePicker +
", Activitate efort :" + radioDaNu +
", tip : '" + tip + '\'' +
", tipm de : " + durata +
", inainte de antrenamnet aveam : " + inainte +
", dupa antrenamnet am : " + dupa +
'}';
}
public Efort(Parcel in) {
this.radioDaNu = in.readString();
this.tip = in.readString();
this.durata = in.readInt();
this.inainte = in.readInt();
this.dupa = in.readInt();
}
public static Parcelable.Creator<Efort> CREATOR = new Creator<Efort>() {
#Override
public Efort createFromParcel(Parcel parcel) {
return new Efort(parcel);
}
#Override
public Efort[] newArray(int i) {
return new Efort[i];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(radioDaNu);
parcel.writeString(tip);
parcel.writeInt(durata);
parcel.writeInt(inainte);
parcel.writeInt(dupa);
}
}
When you called,
finish()
it will stop your activity and finish it. Please remove that finish()
Trying to convert JSON array to list of objects using Gson library.
Code:
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {}; //this line throws the following exception
public class Comment implements Serializable{
#SerializedName("id")
private int mID;
#SerializedName("content")
private String mContent;
#SerializedName("author")
private String mAuthor;
#SerializedName("author_id")
private int mAuthorID;
#SerializedName("author_email")
private String mAuthorEmail;
#SerializedName("date")
private String mDate;
#SerializedName("name")
private String mName;
#SerializedName("image")
private String mImage;
public int getmID() {
return mID;
}
public void setmID(int mID) {
this.mID = mID;
}
public String getmContent() {
return mContent;
}
public void setmContent(String mContent) {
this.mContent = mContent;
}
public String getmAuthor() {
return mAuthor;
}
public void setmAuthor(String mAuthor) {
this.mAuthor = mAuthor;
}
public int getmAuthorID() {
return mAuthorID;
}
public void setmAuthorID(int mAuthorID) {
this.mAuthorID = mAuthorID;
}
public String getmAuthorEmail() {
return mAuthorEmail;
}
public void setmAuthorEmail(String mAuthorEmail) {
this.mAuthorEmail = mAuthorEmail;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmImage() {
return mImage;
}
public void setmImage(String mImage) {
this.mImage = mImage;
}
}
public class CommentListingActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "CommentListingActivity";
private ListView mListViewComments;
private CommentAdapter mCommentAdapter;
private ArrayList<Comment> mCommentList = new ArrayList<Comment>();
private ProgressBar mProgressBar;
private TextView mTextViewErrorMessage;
private Button mButtonRefresh;
private LinearLayout mLinearLayoutError;
private int mPostID;
private boolean isCommentListLoading = true;
private EditText mEditTextComment;
private ImageView mImageViewSend;
private InputMethodManager mInputMethodManager;
private SwipeRefreshLayout mSwipeRefreshLayout;
private boolean mIsRefreshing = false;
private int mOffset = 0;
private View mProgressBarView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_listing);
mPostID = getIntent().getIntExtra("postID",0);
setToolbar();
setToolBarTitle(getString(R.string.commentsLabel));
setToolbarHomeAsUpEnabled(true);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
mIsRefreshing = true;
mOffset = 0;
fetchComments();
}
});
mListViewComments = (ListView) findViewById(R.id.listViewComments);
mCommentAdapter = new CommentAdapter(this, mCommentList,mImageLoader);
mListViewComments.setAdapter(mCommentAdapter);
mProgressBarView = getLayoutInflater().inflate(R.layout.recyclerview_loading_item,null);
mListViewComments.addFooterView(mProgressBarView);
// set the custom dialog components - text, image and button
mEditTextComment = (EditText) findViewById(R.id.editTextComment);
mImageViewSend = (ImageView) findViewById(R.id.imageViewSend);
mImageViewSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postComment();
}
});
mEditTextComment.requestFocus();
mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
initProgressBar();
initErrorView();
mListViewComments.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
mOffset = mOffset + LIST_LIMIT;
mListViewComments.addFooterView(mProgressBarView);
fetchComments();
return true;
}
});
fetchComments();
}
private void fetchComments(){
if (!mIsRefreshing && mCommentAdapter.getCount()==0)
showProgressBar();
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("post",String.valueOf(mPostID));
parameters.put("offset",String.valueOf(mOffset));
NetworkUtility.getJSONRquest(this, APIURLs.LIST_COMMENTS, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Remove loading item
if(mCommentList.size()>0) {
mListViewComments.removeFooterView(mProgressBarView);
}
try {
if(response.getString(API_KEY_STATUS).equalsIgnoreCase(API_RESPONSE_SUCCESS)){
JSONArray jsonArrayComments = response.getJSONArray(API_KEY_DATA);
if(jsonArrayComments.length()>0) {
if (mIsRefreshing) {
mCommentList.clear();
mCommentAdapter.notifyDataSetChanged();
}
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
mCommentList.addAll((Collection<? extends Comment>) GsonUtility.convertJSONStringToObject(jsonArrayComments.toString(), token));
mCommentAdapter.notifyDataSetChanged();
}
mIsRefreshing = false;
if(mCommentAdapter.getCount()>0) {
showContent();
} else {
if (mOffset == 0)
showError("No comments found.");
}
} else {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),response.getString(API_KEY_MESSAGE),getString(R.string.okLabel),null,null,null);
} else
showError(response.getString(API_KEY_MESSAGE));
}
} catch (JSONException e) {
e.printStackTrace();
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(getString(R.string.volleyErrorMessage));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(error.getCause().getMessage());
}
error.printStackTrace();
}
},null,TAG);
}
private void postComment() {
final AppProgressDialog appProgressDialog = new AppProgressDialog(this);
appProgressDialog.setProgressDialogTitle("Posting Comment");
appProgressDialog.setProgressDialogMessage("Please Wait...");
appProgressDialog.showProgressDialog();
try {
final String comment = mEditTextComment.getText().toString();
if (!ValidatorUtility.isBlank(comment) && mPostID!=0) {
JSONObject jsonData = new JSONObject();
jsonData.put("content",comment);
jsonData.put("post",mPostID);
NetworkUtility.postRquestWithBasicAuth(this, APIURLs.POST_COMMENT, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.has("id") && response.getInt("id")>0){
AppToast.toastLong(mContext,"Comment Added");
Comment objComment = new Comment();
if (response.has("author_name"))
objComment.setmAuthor(response.getString("author_name"));
if (response.has("author_email"))
objComment.setmAuthorEmail(response.getString("author_email"));
if (response.has("author"))
objComment.setmAuthorID(response.getInt("author"));
objComment.setmContent(comment);
if (response.has("date"))
objComment.setmDate(response.getString("date"));
if (response.has("id"))
objComment.setmID(response.getInt("id"));
objComment.setmImage(mUser.getImage());
objComment.setmName(mUser.getName());
mCommentList.add(0,objComment);
mCommentAdapter.notifyDataSetChanged();
mEditTextComment.setText(null);
mEditTextComment.clearFocus();
mInputMethodManager.hideSoftInputFromWindow(mEditTextComment.getWindowToken(),0);
showContent();
} else {
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),"Failed to add comment. Please try again later.",getString(R.string.okLabel),null,null,null);
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
appProgressDialog.dismissProgressDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
appProgressDialog.dismissProgressDialog();
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),error.getCause().getMessage(),getString(R.string.okLabel),null,null,null);
}
}, jsonData, TAG);
} else {
appProgressDialog.dismissProgressDialog();
}
} catch (Exception e){
e.printStackTrace();
appProgressDialog.dismissProgressDialog();
}
}
private void initProgressBar(){
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void initErrorView(){
mLinearLayoutError = (LinearLayout) findViewById(R.id.linearLayoutError);
mTextViewErrorMessage = (TextView) findViewById(R.id.textViewErrorMessage);
mButtonRefresh = (Button) findViewById(R.id.buttonRefresh);
mButtonRefresh.setOnClickListener(this);
}
private void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.GONE);
}
private void showContent(){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.VISIBLE);
}
private void showError(String message){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.GONE);
mTextViewErrorMessage.setText(message);
}
#Override
public void onClick(View view) {
if(view == mButtonRefresh){
fetchComments();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
KeyboardUtility.closeKeyboard(this,mEditTextComment);
}
}
Exception:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate app.govindaconnect.mangaltaraproductions.com.views.CommentListingActivity$4$1.toString()
Only 1 JSON objects get converted and added to the list.
What might be causing the exception? Because this is not happening with other classes.
You can try this
replace this line
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
with this and try
Type token = new TypeToken<List<Comment>>() {}.getType();
List<Comment> commentsList = gson.fromJson(String.valueOf(resultArray), type);
I took JSON array in a string variable and then it started working.
why don't you try Jackson parser for conversion, it's much simpler and easier
example for you :
List<Comment> list=null;
String json="your json array";
ObjectMapper mapper = new ObjectMapper();
try {
list= mapper.readValue(json, new TypeReference<List<Comment>>(){});
} catch (IOException e) {
throw new Exception(e);
}