I'm creating an event app which contains a list of events in recyclerview.
The events recyclerview consists of the event name, image, date and time, heart image (example: heart shape like button on Instagram) which will change its color when the user clicks on the 'interested' button.
After clicking on any event its description appears and there are two buttons: 'interested' and 'going'. If the user clicks on 'interested' that heart color in the recyclerview will become yellow. The event will also get saved in another list where it will remain until that event is removed from the saved list.
So far I've completed saving that event in the saved list on clicking the 'interested' button. But I don't know how to change the heart color simultaneously and how to make it remain until the event is deleted from saved list.
First Activity calling recyclerview adapter
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class EventActivity extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private static final String URL_PRODUCTS = "https://www.test.magicalballoons.co.in/priyanka/event.php?";
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
ImageView homemenu;
//SwipeRefreshLayout swiper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
getSupportActionBar().hide();
homemenu = findViewById(R.id.homemenu);
// swiper = findViewById(R.id.swiper);
//getting the recyclerview from xml
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
productList.add(new Product(
product.getString("id"),
product.getString("name"),
product.getString("date"),
product.getString("location"),
product.getString("image"),
product.getString("details")
));
}
//creating adapter object and setting it to recyclerview
RecyclerViewAdapter adapter = new RecyclerViewAdapter(EventActivity.this, productList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EventActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void onBackPressed() {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Recyclerview Adapter
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.BreakIterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static com.example.priyankaregistration.URLs.URL_EVENT;
/**
* Created by Aws on 11/03/2018.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private RequestQueue requestQueue;
private JsonArrayRequest request;
private Context mContext;
private List<Product> mData;
RequestOptions option;
TextView total;
ImageView colorheart,heart;
// Dialog myDailog;
private Dialog myDialog;
public RecyclerViewAdapter(Context mContext, List<Product> mData) {
this.mContext = mContext;
this.mData = mData;
//this.swiper = swiper;
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.fragment_conferences, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
myDialog = new Dialog(mContext);
colorheart = (ImageView) view.findViewById(R.id.colorheart);
heart = (ImageView) view.findViewById(R.id.heart);
total = (TextView) view.findViewById(R.id.count);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_COUNT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
total.setText(jsonObject.getString("countid"));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("eventid", mData.get(viewHolder.getAdapterPosition()).getId());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(stringRequest);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, Description.class);
intent.putExtra("eventname",mData.get(viewHolder.getAdapterPosition()).getName());
intent.putExtra("eventid",mData.get(viewHolder.getAdapterPosition()).getId());
intent.putExtra("eventdate",mData.get(viewHolder.getAdapterPosition()).getDate());
intent.putExtra("eventloc",mData.get(viewHolder.getAdapterPosition()).getLocation());
intent.putExtra("eventimg",mData.get(viewHolder.getAdapterPosition()).getImage());
intent.putExtra("details",mData.get(viewHolder.getAdapterPosition()).getDetails());
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textViewName.setText(mData.get(position).getName());
holder.textViewDate.setText("Date : " + mData.get(position).getDate());
holder.textViewLocation.setText("Time : " + mData.get(position).getLocation());
Glide.with(mContext).load(mData.get(position).getImage()).apply(option).into(holder.img_thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView textViewName,textViewDate, textViewLocation,total;
ImageView img_thumbnail;
//LinearLayout view_container;
CardView view_container;
public MyViewHolder(View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.container);
textViewName = itemView.findViewById(R.id.textViewName);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewLocation = itemView.findViewById(R.id.textViewLocation);
total = itemView.findViewById(R.id.count);
img_thumbnail=itemView.findViewById(R.id.imageView);
}
}
}
This is second activity
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.Snackbar;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Description extends AppCompatActivity {
TextView textViewName,textViewDate, textViewLocation, details;
ImageView evimg,going,interest;
RequestOptions option;
ImageView homemenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
getSupportActionBar().hide();
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
textViewName = findViewById(R.id.textViewName);
evimg = findViewById(R.id.evimg);
details = findViewById(R.id.details);
going = findViewById(R.id.going);
interest = findViewById(R.id.interest);
homemenu = findViewById(R.id.homemenu);
textViewName.setText(getIntent().getStringExtra("eventname"));
//textViewDate.setText(getIntent().getStringExtra("eventdate"));
//textViewLocation.setText(getIntent().getStringExtra("eventloc"));
details.setText(getIntent().getStringExtra("details"));
details.setMovementMethod(new ScrollingMovementMethod());
Glide.with(this).load(getIntent().getStringExtra("eventimg")).apply(option).into(evimg);
going.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.URL_EVENT+"?userid=" + SharedPrefManager.getInstance(getApplicationContext()).getUserId() + "&eventid="+ getIntent().getStringExtra("eventid"),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("name");
Intent intent = new Intent(Description.this,Ticket.class);
intent.putExtra("code",message);
intent.putExtra("eventimg",getIntent().getStringExtra("eventimg"));
intent.putExtra("activity","NO");
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
jsonrequest();
startActivity(intent);
finish();
//Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
//params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
interest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTSAVED ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
//String message = jsonObject.getString("name")
Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Description.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void jsonrequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTDELETED,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(),jsonObject.getString("Event removed from saved list"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
//progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
I'm having heart image in my recyclerview . And when i click on interest buttton in Description activity the heart image in recyclerview get change.
Assuming you are saving the events in some model class, what you can do is when calling the onBindViewHolder method of your adapter, check if the event is marked as save. If it is, then you either need to change the heart image to another heart image which is yellow, or you can apply a tint on the heart image to make it yellow.
You can change drawable by using this code
heartImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.yellow_heart));
You can apply tint by using this code
heartImageView.setColorFilter(Color.argb(255, 255, 255, 0))
EDIT (Based on comment)
If the heart is in the first activity and the interested button is in the second activity what you need to do is to save the state of the event when you click on the interested button. Once you go back to the the first activity, you can check the state of the event and then update the image by using any of the above two methods.
EDIT 2 (Based on new code shared)
After you get the response from your Volley call, you should save the event id somewhere to keep track of which events you are interested in (this can be in either a model class or some global list). When you go back to your first activity (which contains the recyclerview), you need to check each event id with the stored event id list that you have and change the heart for each event that matches.
You can do this with the help for startActivityforresult
In Activity1, start Activity2 as:
Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);
In Activity2, use setResult for sending data back:
Intent intent = new Intent();
intent.putExtra("updatedArraylist", "arraylist")
setResult(RESULT_OK, intent);
finish();
And in Activity1, receive data with onActivityResult:
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String strArrayList =
data.getStringExtra("updatedArraylist");
Gson gson = new Gson();
Type youListType = new TypeToken<List<Model>>() {
}.getType();
List<Model> yourTypeList = gson.fromJson(strArrayList,
yourListType);
ArrayList finalArraylist = new ArrayList<>(yourTypeList);
yourArraylist.addAll(finalArraylist);
youtAdapter.notifyDataSetChanged();
}
}
}
You can apply color onclick event to heart button like following code :
your_image_id.setBackgroundColor(getResources().getColor(R.color.yellow));
In first activity
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, 100);
From second activity, you have to execute the below code before the activity getting destroyed by finish() or back press (For this you can override onBackPressed of second activity and remove the super class call and call the below method).
private void exitWithResult(){
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Id of selected item");
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
Again in first activity you have to handle the result inside onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
Log.e("DATA", "" + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
Log.e("DATA", "No result");
}
}
}
Update
You can use an interface as callback from adapter to activity. startActivityForResult canbe called inside the callback method of interface. You have to pass callback interface to adapter through adapter constructor along with data set.
declare this interface inside adapter
public interface AdapterCallback{
void onAdapterSelected(int pos);
}
And in first activity implement the interface like this.
MyAdapter.AdapterCallback callback = new MyAdapter.AdapterCallback() {
#Override
public void onAdapterSelected(int pos) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivityForResult(intent, 100);
}
};
Then set adapter like this.
RecyclerView rv = findViewById(R.id.rv_list);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
MyAdapter adapter = new MyAdapter(callback); //This is the only change
rv.setAdapter(adapter);
Changes in adapter below. (You should pass list data along with call back as you already does)
private AdapterCallback callback;
public MyAdapter(AdapterCallback callback) {
this.callback = callback;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int i) {
viewHolder.mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onAdapterSelected(i);
}
});
}
Interface also come inside adapter. I am not repeating it here as i already mentioned at first
Related
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
I am not able to update the values when i click on the search button, The data is fetched but the old fetched data is not getting discards, the fetched data is overlapping over each other
SearchFragment.java
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
private String Api_id= "3f335994";
private String Api_key = "8e99e327d1f2130dc6ab3422e26a95e8";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "https://api.edamam.com/search?q=" + query + "&app_id=" + Api_id + "&app_key=" + Api_key;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i =0;i<hits.length();i++) {
JSONObject jsonObject = hits.getJSONObject(i);
JSONObject recipe = jsonObject.getJSONObject("recipe");
String recipe_img = recipe.getString("image");
String recipe_title = recipe.getString("label");
String recipe_data = recipe.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(),recipeList);
recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonObjectRequest);
/*JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
Log.d("data",recipe_title);
}
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});*/
/*jsonArrayRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 3000;
}
#Override
public int getCurrentRetryCount() {
return 3000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});*/
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I want to get rid of the old data after the new data is fetched and don't want to display it after the new one is called
looks like you are only adding items to your ArrayList<Recipe> recipeList;, so they may duplicate
maybe try to recipeList.clear(); it in first line of onResponse method
also notifyDataSetChanged isn't needed, setAdapter does it itself (and a lot more in fact)
Here is my main file where i get u_id and other data but i pass u_id text to other activity
Mainactivity.java
package com.desktop.app;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.desktop.app.Stitle.EXTRA_TITLE;
public class MainActivity extends AppCompatActivity {
Button signup,login,learnmore ;
EditText ed1,ed2,u_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (Button) findViewById(R.id.signupbutton);
learnmore = (Button) findViewById(R.id.learnmore);
login = (Button) findViewById(R.id.loginbutton);
ed1 = (EditText) findViewById(R.id.emailedittext);
u_id = (EditText) findViewById(R.id.uid);
ed2 = (EditText) findViewById(R.id.passwordedittext);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity2.class);
startActivity(in);
}
});
learnmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity1.class);
startActivity(in);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
return;
}
if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
return;
}
if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
return;
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
}
});
}
private void login(){
String url= "http://192.168.0.136/fyp/andr_log.php";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("Login Successfull")){
Toast.makeText(getApplicationContext(), "Login Successfull",Toast.LENGTH_LONG).show();
Intent in = new Intent(MainActivity.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Login Unsuccessfull",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", ed1.getText().toString().trim() );
params.put("uid", u_id.getText().toString().trim() );
params.put("Password", ed2.getText().toString().trim() );
return params;
}
};
requestQueue.add(stringRequest);
}});
}
}
fullview.java
package com.desktop.app;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.support.v7.app.AlertDialog.*;
import static com.desktop.app.Stitle.EXTRA_AUTHOR;
import static com.desktop.app.Stitle.EXTRA_HR;
import static com.desktop.app.Stitle.EXTRA_PUBLISHER;
import static com.desktop.app.Stitle.EXTRA_PUBY;
import static com.desktop.app.Stitle.EXTRA_ACC;
import static com.desktop.app.Stitle.EXTRA_RAK;
import static com.desktop.app.Stitle.EXTRA_STATUS;
import static com.desktop.app.Stitle.EXTRA_TITLE;
import static com.desktop.app.Stitle.EXTRA_VR;
public class fullview extends AppCompatActivity {
Button location, avail, request;
TextView textviewtitle, textviewauthors, textviewpublisher, textviewpubyear,textviewacc,u_id;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullview);
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
String title = intent.getStringExtra(EXTRA_TITLE);
String author = intent.getStringExtra(EXTRA_AUTHOR);
String publisher = intent.getStringExtra(EXTRA_PUBLISHER);
int puby = intent.getIntExtra(EXTRA_PUBY,0);
int accc = intent.getIntExtra(EXTRA_ACC,0);
final int rak = intent.getIntExtra(EXTRA_RAK,0);
final int hr = intent.getIntExtra(EXTRA_HR,0);
final int vr = intent.getIntExtra(EXTRA_VR,0);
final String status = intent.getStringExtra(EXTRA_STATUS);
textviewtitle = findViewById(R.id.textviewtitle);
textviewauthors = findViewById(R.id.textviewauthors);
textviewpublisher = findViewById(R.id.textviewpublisher);
textviewpubyear = findViewById(R.id.textviewpubyear);
textviewacc = findViewById(R.id.textviewacc);
textviewtitle.setText(title);
textviewauthors.setText(author);
textviewpublisher.setText(publisher);
textviewpubyear.setText(String.valueOf(puby));
textviewacc.setText(String.valueOf(accc));
location = findViewById(R.id.loc);
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
builder.setTitle("Location");
builder.setMessage("Rak-No :: " + rak + "\nColumn :: " + hr +"\nRow :: " + vr);
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
}
});
avail = findViewById(R.id.avail);
avail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
{
if (status.equals("yes")) {
builder.setTitle("Availablity");
builder.setMessage("Available");
} else {
builder.setTitle("Availablity");
builder.setMessage("Not Available");
}
}
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
});
request= findViewById(R.id.request);
request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request();
}
});
}
private void request(){
String url= "http://192.168.0.136/fyp/bookreq.php";
final RequestQueue requestQueue = Volley.newRequestQueue(fullview.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("successfull")){
Toast.makeText(getApplicationContext(), "Go to Admin For Approval",Toast.LENGTH_LONG).show();
Intent in = new Intent(fullview.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Already Requested",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", textviewtitle.getText().toString().trim());
params.put("Author", textviewauthors.getText().toString().trim());
params.put("Publisher", textviewpublisher.getText().toString().trim());
params.put("Acc", textviewacc.getText().toString().trim());
params.put("Puby", textviewpubyear.getText().toString().trim());
Log.i("Info",textviewtitle.getText().toString().trim());
return params;
}
};
requestQueue.add(stringRequest);
}
}
Here is my second file above where i want to shoe u_id text but i done with this to pass u_id text to other activity
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
this code i use to pass u_id text and next activity code i use below code
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
This is what your problem is.
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
Change this line
b.putString("text", String.valueOf(u_id));
to
b.putString("text", u_id.getText().toString().trim());
EDIT:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
}else if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
} else if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
} else {
login();
Intent i = new Intent(MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", u_id.getText().toString().trim());
i.putExtras(b);
startActivity(i);
}
}
I can't solve this problem in my new app. I am a beginner in Android Studio. My register.java class file is added here:
package com.agte.agtevivo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class Register extends AppCompatActivity {
Button button;
EditText editText3,editText4,editText5,editText6,editText7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editText3 =(EditText)findViewById(R.id.editText3);
editText4=(EditText)findViewById(R.id.editText4);
editText5 =(EditText)findViewById(R.id.editText5);
editText6=(EditText)findViewById(R.id.editText6);
editText7=(EditText)findViewById(R.id.editText7);
button=(Button)findViewById(R.id.button);
//button.setOnClickListener(this);
button.setOnClickListener(new View.OnClickListener(){
// #Override
public void onClik(View v){
final String name=editText3.getText().toString();
final String username=editText4.getText().toString();
final int number=Integer.parseInt(editText7.getText().toString());
final String shop=editText5.getText().toString();
final String password=editText6.getText().toString();
Response.Listener<String> responceListener =new Response.Listener<String>(){
// #Override
public void onResponce (String responce){
try {
JSONObject jsonResponce =new JSONObject(responce);
boolean success=new jsonResponce("Registerd Successfully");
if(success)
{
Intent intent =new Intent(Register.this,Login.class);
Register.this.startActivity(intent);
}else{
AlertDialog.Builder builder =new AlertDialog.Builder(Register.this);
builder.setMessage("Register Failed");
//.setNegativeButton("Retry",null);
//.create()
//.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
};
};
RegisterRequest registerRequest =new RegisterRequest
(name,username,number,shop,password,responceListener);
RequestQueue queue = Volley.newRequestQueue(Register.this);
queue.add(registerRequest);
}
});
}
/* #Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button:
break;
}
}
*/
}
I got an error I have listed on below:
Error:(38, 62) error: is not
abstract and does not override abstract method onClick(View) in
OnClickListener
Error:(48, 93) error: is
not abstract and does not override abstract method
onResponse(String) in Listener
Error:(53, 50) error: cannot find symbol class jsonResponce
Error:Execution failed for task
':app:compileFlavorDebugJavaWithJavac'. Compilation failed; see the
compiler error output for details.
Currently I got an error:
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = new jsonResponse.getBoolean("Success");
if (success) {
Intent intent = new Intent(Register.this, Login.class);
Register.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setMessage("Register Failed");
//.setNegativeButton("Retry",null);
//.create()
//.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Error is:
Error:Execution failed for task ':app:compileFlavorDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Error:(62, 47) error: incompatible types
required: boolean
found: getBoolean
package com.agte.agtevivo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class Register extends AppCompatActivity {
Button button;
EditText editText3,editText4,editText5,editText6,editText7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editText3 =(EditText)findViewById(R.id.editText3);
editText4=(EditText)findViewById(R.id.editText4);
editText5 =(EditText)findViewById(R.id.editText5);
editText6=(EditText)findViewById(R.id.editText6);
editText7=(EditText)findViewById(R.id.editText7);
button=(Button)findViewById(R.id.button);
//button.setOnClickListener(this);
button.setOnClickListener(new View.OnClickListener(){
// #Override
public void onClick(View v){
final String name=editText3.getText().toString();
final String username=editText4.getText().toString();
final int number=Integer.parseInt(editText7.getText().toString());
final String shop=editText5.getText().toString();
final String password=editText6.getText().toString();
Response.Listener<String> responceListener =new Response.Listener<String>(){
#Override
public void onResponse (String responce){
try {
JSONObject jsonResponce =new JSONObject(responce);
// What is this ?
boolean success=new jsonResponce("Registerd Successfully");
if(success)
{
Intent intent =new Intent(Register.this,Login.class);
Register.this.startActivity(intent);
}else{
AlertDialog.Builder builder =new AlertDialog.Builder(Register.this);
builder.setMessage("Register Failed");
//.setNegativeButton("Retry",null);
//.create()
//.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
};
};
RegisterRequest registerRequest =new RegisterRequest
(name,username,number,shop,password,responceListener);
RequestQueue queue = Volley.newRequestQueue(Register.this);
queue.add(registerRequest);
}
});
}
/* #Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button:
break;
}
}
*/
}
Theres a load of grammar failures in your code, which I corrected in the snipped above (just make a diff) for further debugging look here: https://developer.android.com/studio/debug/index.html
In this fragment I send a jsonRequest with volley to the server . and I'm setting the swipeRefreshLayout to this fragment , I want to load only new json data but when I use sendJsonRequest() method on the onRefresh() all of the json data is enabled to the recyclerView:
This is my fragment code:
package ghandak.ghandshekan.com.ghandak.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import ghandak.ghandshekan.com.ghandak.R;
import ghandak.ghandshekan.com.ghandak.adapters.PostRecyclerAdapter;
import ghandak.ghandshekan.com.ghandak.app.AppController;
import ghandak.ghandshekan.com.ghandak.models.PostData;
/**
* Created by imajid on 12/19/2015.
*/
public class TabFragment3 extends Fragment implements OnRefreshListener{
private RecyclerView allContentRecyclerView;
private String url = "http://kakdo.herokuapp.com/api/news/?format=json";
private List<PostData> postDataList = new ArrayList<PostData>();
private SwipeRefreshLayout swipeRefreshLayout;
//====================================================================================== onCreateView
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_3 , container , false);
allContentRecyclerView = (RecyclerView)view.findViewById(R.id.xmlRecyclerViewtabFragment3);
allContentRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.xml_swipe_refresh_layout_tab_fragment_3);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
//swipeRefreshLayout.setColorSchemeColors();
return view;
}
//====================================================================================== onCreate
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendJsonRequest();
}
//====================================================================================== sendjsonRequest
private void sendJsonRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseJsonResponse(response);
//==========setting adapter to the recyclerview <==
allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(request);
}
//====================================================================================== parsjsonResponse()
private void parseJsonResponse(JSONArray response) {
if(response == null){
Toast.makeText(getActivity(), "ریسپانس خالی هستش", Toast.LENGTH_SHORT).show();
return;
}else {
Log.d("parsejsonresponse", "response khali nist");
for (int i = 0 ; i < response.length() ; i++ ){
try {
//Toast.makeText(getActivity(), "ریسپانس میگیرم ", Toast.LENGTH_SHORT).show();
JSONObject currentPost = response.getJSONObject(i);
//Log.d("currentPost", "currentPost ro gereftam");
PostData postData = new PostData();
postData.setTitle(currentPost.getString("title"));
//Toast.makeText(getActivity() , currentPost.getString("title") , Toast.LENGTH_SHORT).show();
postData.setCreate(currentPost.getString("create"));
postDataList.add(postData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onRefresh() {
sendJsonRequest();
swipeRefreshLayout.setRefreshing(false);
}
}
Now my question is in the OnRefresh method , what can I write to load only new json data, not all of the exists json.
Add this line in your code
postDataList.clear(); in your code given in bellow.
Updated:
#Override
public void onResponse(JSONArray response) {
if(response == null )
return;
postDataList.clear();
parseJsonResponse(response);
//==========setting adapter to the recyclerview <==
allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
}
Note: when ever you create any kind of list max create adapter instance once in your code, After change list data you just need to call 'adapterInstance.notifyDataSetChange();'
This is the best practice instead of creating list every time it's better to refresh list items, Further info check here
add this code ,
private SwipeRefreshLayout mSwipeRefreshLayout;
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
}, SPLASH_DISPLAY_LENGTH);
}
});
when you want to refresh it call,
mSwipeRefreshLayout.setRefreshing(true);
swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new OnRefreshListener()
{
#Override
public void onRefresh()
{
//clear your old data
callForData();
//swipeContainer.setRefreshing(false); use this while get data and set in you ui
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);