I have a recyclerView and customAdaprer. I pass an list of an object (earthquakeList)to recycleradapter and then i do setAdapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}
I create AsyncTask on onResume method:
#Override
protected void onResume() {
super.onResume();
// Kick off an {#link AsyncTask} to perform the network request
new EarthQuakeAsyncTask().execute();
}
in AsyncTask my class i get a new List from my object that i get from internet and when I replaced this new list with older list and call notifyDataSetChanged, recyclerView still nothing show??
I debug my app and I get object from net.
I do in this way on list view but recylerview seems efferent.
I replace old list with the new list one like blow:
private class EarthQuakeAsyncTask extends AsyncTask<Void, Void, List<Earthquake>> {
#Override
protected List<Earthquake> doInBackground(Void... urls) {
// Create URL object
URL url = HttpRequest.createUrl(USGS_REQUEST_URL);
// perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = HttpRequest.makeHttpRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
List<Earthquake> earthquakes = HttpRequest.extractFeaturesFromJson(jsonResponse);
return earthquakes;
}
#Override
protected void onPostExecute(List<Earthquake> earthquakeList) {
super.onPostExecute(earthquakeList);
MainActivity.this.earthquakeList.clear();
MainActivity.this.earthquakeList.addAll(earthquakeList);
adapter.notifyDataSetChanged();
}
what is exactly my wrong?
************************ EDIT ********************
this is Adapter :
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {
List<Earthquake> earthquakes;
public RecyclerViewAdapter(List<Earthquake> earthquakes) {
this.earthquakes = earthquakes;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.earthquak_list_item, parent, false);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
Earthquake earthquake = earthquakes.get(position);
holder.magnitude.setText(earthquake.getmMagnitude());
holder.location.setText(earthquake.getmLocation());
holder.time.setText(earthquake.getmDate());
}
#Override
public int getItemCount() {
return (null != earthquakes ? earthquakes.size() : 0);
}
public void setItems(List<Earthquake> earthquakeList) {
this.earthquakes = earthquakeList;
}
public class MyHolder extends RecyclerView.ViewHolder {
#BindView(R.id.magnitude)
TextView magnitude;
#BindView(R.id.location)
TextView location;
#BindView(R.id.date)
TextView time;
public MyHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
Ops ,I forgot put LayoutManager for recyclerView .
this is right code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}
Related
Hello everyone i am getting the messages of the users in android studio for that i am refreshing the recyclerview every second but the probem is scrolling when i am scrooling the recyclerview to old messages then its not scrooling becouse of the getting data every second can someone please help me in this
bellow is my activity code
public class Message_User_Activity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
content();
Clicks();
}
public void content()
{
getdata();
refresh(100);
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
toolbar_user_name.setText(name);
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
}
below is my adapter code
public class Message_user_Adapter extends RecyclerView.Adapter<Message_user_Adapter.Message_user_Adapter_View_Holder>
{
List<responsemodel> data;
String mmessage_To;
public Message_user_Adapter(List<responsemodel> data, String message_To) {
this.data = data;
this.mmessage_To = message_To;
}
#NonNull
#Override
public Message_user_Adapter_View_Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_messages_layout,parent,false);
return new Message_user_Adapter_View_Holder(view);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull Message_user_Adapter_View_Holder holder, int position) {
String time = calculateTime(data.get(position).getMessage_Time());
if (data.get(position).getMessage_From().equals(mmessage_To))
{
holder.other_user_message_message_layout.setVisibility(View.VISIBLE);
holder.other_user_message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.GONE);
}
else
{
holder.other_user_message_message_layout.setVisibility(View.GONE);
holder.message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
private String calculateTime(String post_time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
long time = sdf.parse(post_time).getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago+"";
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
public int getItemCount() {
return data.size();
}
public String getdata() {
return mmessage_To.toString();
}
class Message_user_Adapter_View_Holder extends RecyclerView.ViewHolder
{
TextView other_user_message_message_layout;
TextView message_message_layout;
CircleImageView toolbar_user_profile;
public Message_user_Adapter_View_Holder(#NonNull View itemView) {
super(itemView);
other_user_message_message_layout = itemView.findViewById(R.id.other_user_message_message_layout);
message_message_layout = itemView.findViewById(R.id.message_message_layout);
}
}
}
According to my simple information
in your getdata() function. you send new data to Message_user_Adapter of RecyclerView every time you receive data from API or whatever you use ,so the data of adapter every second is change to new data ,so the RecyclerView being recreated every second with new data and the scroll will not work
just try to outage this lines from onResponse to the first of getdata():
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
and in its place add this line to notify the adapter about changed data :
adapter.notifyDatasetChanged()
something like this :
private void getdata() {
toolbar_user_name.setText(name);
String Choice = "Get Messages";
List<responsemodel> data = new ArrayList<>();//this line was change
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);//this line was change
messages_Message_user_RecyclerView.setAdapter(adapter);//this line was change
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
data = response.body();
adapter.notifyDatasetChanged()//this line was added
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
i am getting messages from the database into a recycler view but i want to refresh the recycler view every second for to adding different for to getting new messages in recycler view
But i haver an error of getting data please see it https://www.filemail.com/d/izhittgyibvcjxx
my code is
boolean refresh;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
refresh = true;
content();
}
public void content()
{
getdata();
if (refresh)
{
refresh(100);
}
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.smoothScrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount());
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
I try to do recyclerView with retrofit2, but I do in my code: recyclerView Adapter Constructor and I get a error in my MainActivity part of this line -
"(flowersList, this)": I get error: List anonymous retrofit2.Callback
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
my code my MainActivity is:
try {
APIService service = ApiClient.getRetrofit().create(APIService.class);
retrofit2.Call<List<Flower>> call = service.getFlowerData();
call.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(retrofit2.Call<List<Flower>> call, Response<List<Flower>> response) {
List<Flower> flowersList = response.body();
mLinearLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
mRecyclerView.setAdapter(recyclerViewAdapter);
}
and the code in RecyclerViewFlowersAdapter is:
public class RecyclerViewFlowersAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private List<Flower> mFlowers;
private Context mContext;
public RecyclerViewFlowersAdapter(List<Flower> flowers, Context context) {
mContext = context;
mFlowers = flowers;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.flower_item_card, null);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.mTextViewTitle.setText(mFlowers.get(position).getName());
Picasso.with(mContext)
.load(mFlowers.get(position).getPhoto()).into(holder.mImageViewFlower);
}
#Override
public int getItemCount() {
return mFlowers.size();
}
}
and my code in RecyclerViewHolder is:
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextViewTitle;
public ImageView mImageViewFlower;
public RecyclerViewHolder(View itemView){
super(itemView);
itemView.setOnClickListener(this);
mTextViewTitle = itemView.findViewById(R.id.title);
mImageViewFlower = itemView.findViewById(R.id.imageViewFlower);
}
#Override
public void onClick(View v) {
}
}
I try to do alot of thing but is still error.
thanks for help :)
You are probably using a wrong context, try using MainActivity.this instead of this. Change this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
to this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, MainActivity.this);
I want to send a json object to the server using the post method.
I have used volley library to pass the string params, and it's working fine, but when I run my app I am getting this:
BasicNetwork.performRequest: Unexpected response code 400
my code:-
public class MainActivity extends AppCompatActivity {
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
makeJsonObjReq();
}
private void makeJsonObjReq() {
JSONObject request=new JSONObject();
try {
request.put("ProductCode", "KK03672-038");
} catch (JSONException e) {
e.printStackTrace();
}
pd = ProgressDialog.show(MainActivity.this, "Alert", "Please Wait...");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
"URL",request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pd.dismiss();
System.out.println("Response is====>" + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
System.out.println("Error is====>" + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
// Adding request to request queue:-
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
}
AppContoller:-
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Try adding volley initialization code in Application class and reference this to your manifest application tag.
Hi everybody!!
I have two fragments:Fragment1 and Fragment2; Fragment1 contains Json,and after getting Json, I replace Fragment1 to Fragment2 via .replace(..) and transfer the Json via Bundle.
My Goal is: Refresh Json in Fragment1 each 60s for example and update automatically Fragment2 but i don't know how to do that!! i need your help!!
this is my code:
Class Fragment1
public class Fragment1 extends Fragment implements OnClickListener{
public static final String IMAGE_RESOURCE_ID="iconResourceID";
public static final String ITEM_NAME="itemName";
Button btnvalider;
//test transfer variable entre fragment
public Communicator com;
public void setCom(Communicator com) {
this.com = com;
}
/*
* Test Jsonparser
*
*/
Context c;
private ProgressDialog pDialog;
public String testfinalewa="";
JSonParser jsonParser = new JSonParser();
// url to create new product
private static String url_create_product = "http://10.0.2.2/webservice/create_personne.php";
public String getTestfinalewa() {
return testfinalewa;
}
public void setTestfinalewa(String testfinalewa) {
this.testfinalewa = testfinalewa;
}
// JSON Node names
private static final String TAG_SUCCESS = "success";
//fin test json
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
c=getActivity();
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
btnvalider=(Button)getActivity().findViewById(R.id.button1);
btnvalider.setOnClickListener(this);
this.com=(Communicator) getActivity();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
public void run() {
// call JSON methods here
new AttemptLogin().execute();
}
}, 1 );
}
//interface pour transferer variable entre fragment
public interface Communicator{
public void respond(String data);
}
class AttemptLogin extends AsyncTask<String, String, String>{//<params,progress,result>
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(c);
pDialog.setMessage("Chargement...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String name ="test";// pseudo.getText().toString();
String moddepasse = "test";//mdp.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
Log.i("misy ve", "ok="+moddepasse);
Log.i("misy ve", "ok="+name);
params.add(new BasicNameValuePair("moddepasse", moddepasse));
Log.i("test", "mbola tena mety eto 1");
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Create Response", json.toString());
Log.i("test", "mbola tena mety eto");
try {
int success = json.getInt(TAG_SUCCESS);
String succ=json.getString("ok");
Log.i("milay", succ);
if ((success == 1)) {
Log.i("accepter", "mdp correct");
} else {
Log.i("pas accepter", "non correct");
}
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
protected void onPostExecute(String result) {
pDialog.dismiss();
com.respond(result);
Fragment2 fb=new Fragment2();
FragmentTransaction t=getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("mondata", result);
fb.setArguments(args);
t.replace(R.id.myFramePrincipal, fb).commit();
}
}
}
class Fragment2
public class Fragment2 extends Fragment{
TextView text;
String aa;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
text=(TextView) getActivity().findViewById(R.id.textView1);
text.setText(getArguments().getString("mondata"));
}
public void refreshData(String data) {
aa= new String(data);
//aa.notifyDataSetChanged();
text.setText(aa);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_3, container, false);
}
public void ChangerText(String data) {
text.setText(data);
}
}
Thanks for your help!!