I am displaying a list of messages in my chat room and I'm using RecycleView to display. I want the view to be set to the recent message(last message, last item in the list) instead of the first item. I used smoothScrollToPosition but I don't want the list to be scrolled from first to last to view the recent message. I want it to be like whatsapp which when clicked on a chat would show the view of the last message. How can I achieve this?
package com.webapp.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.webapp.chat.R;
import com.webapp.chat.adapter.ChatRoomThreadAdapter;
import com.webapp.chat.app.Config;
import com.webapp.chat.app.EndPoints;
import com.webapp.chat.app.MyApplication;
import com.webapp.chat.gcm.NotificationUtils;
import com.webapp.chat.model.Message;
import com.webapp.chat.model.User;
public class ChatRoomActivity extends AppCompatActivity {
private String TAG = ChatRoomActivity.class.getSimpleName();
private String userChatRoomId;
private RecyclerView recyclerView;
private ChatRoomThreadAdapter mAdapter;
private ArrayList<Message> messageArrayList;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private EditText inputMessage;
private Button btnSend;
private String selfUserId;
private String selfUserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputMessage = (EditText) findViewById(R.id.message);
btnSend = (Button) findViewById(R.id.btn_send);
Intent intent = getIntent();
userChatRoomId = intent.getStringExtra("user_id");
String title = intent.getStringExtra("name");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (userChatRoomId == null) {
Toast.makeText(getApplicationContext(), "User Chat room not found!", Toast.LENGTH_SHORT).show();
finish();
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
messageArrayList = new ArrayList<>();
// self user id is to identify the message owner
selfUserId = MyApplication.getInstance().getPrefManager().getUser().getId();
selfUserName = MyApplication.getInstance().getPrefManager().getUser().getName();
mAdapter = new ChatRoomThreadAdapter(this, messageArrayList, selfUserId);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push message is received
handlePushNotification(intent);
}
}
};
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
fetchChatThread();
}
#Override
protected void onResume() {
super.onResume();
// registering the receiver for new notification
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
/**
* Handling new push message, will add the message to
* recycler view and scroll it to bottom
* */
private void handlePushNotification(Intent intent) {
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
messageArrayList.add(message);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}
}
}
/**
* Posting a new message in chat room
* will make an http call to our server. Our server again sends the message
* to all the devices as push notification
* */
private void sendMessage() {
final String message = this.inputMessage.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
Toast.makeText(getApplicationContext(), "Enter a message", Toast.LENGTH_SHORT).show();
return;
}
/** Create chatroom with the other user after sending the message**/
String endPointInsert = EndPoints.CHAT_ROOM.replace("_ID_", selfUserId) + "/" + userChatRoomId;
Log.e(TAG, "endpointInsert: " + endPointInsert);
StringRequest strReque = new StringRequest(Request.Method.GET,
endPointInsert, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Date date = new Date();
String createdAt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
Log.e(TAG, "TIMESTAMP:" + createdAt);
User user = new User(selfUserId, selfUserName);
final Message msg = new Message();
msg.setId("");
msg.setMessage(message);
msg.setCreatedAt(createdAt);
msg.setUser(user);
messageArrayList.add(msg);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
// scrolling to bottom of the recycler view
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}
//Log.e(TAG,msg.getId());
String endPoint = EndPoints.USER_MESSAGE.replace("_ID_", userChatRoomId);
Log.e(TAG, "endpoint: " + endPoint);
this.inputMessage.setText("");
StringRequest strReq = new StringRequest(Request.Method.POST,
endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
JSONObject commentObj = obj.getJSONObject("message");
String commentId = commentObj.getString("message_id");
String commentText = commentObj.getString("message");
String createdAt = commentObj.getString("created_at");
JSONObject userObj = obj.getJSONObject("user");
String userId = commentObj.getString("from_user_id");
String userName = userObj.getString("name");
User user = new User(userId, userName);
Log.e(TAG, commentId);
msg.setId(commentId);
/*Message message = new Message();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createdAt);
message.setUser(user);*/
/*messageArrayList.add(msg);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
// scrolling to bottom of the recycler view
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}*/
} else {
Toast.makeText(getApplicationContext(), "" + obj.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
inputMessage.setText(message);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", MyApplication.getInstance().getPrefManager().getUser().getId());
params.put("message", message);
Log.e(TAG, "Params: " + params.toString());
return params;
};
};
// disabling retry policy so that it won't make
// multiple http calls
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReque);
MyApplication.getInstance().addToRequestQueue(strReq);
Log.i(TAG,msg.getId());
}
/**
* Fetching all the messages of a single chat room
* */
private void fetchChatThread() {
String endPointi = EndPoints.CHAT_USER_THREAD.replace("_ID_", userChatRoomId);
String endPoint = endPointi + "/" + selfUserId;
Log.e(TAG, "endPoint: " + endPoint);
StringRequest strReq = new StringRequest(Request.Method.GET,
endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("message_id");
String commentText = commentObj.getString("message");
String createdAt = commentObj.getString("created_at");
JSONObject userObj = commentObj.getJSONObject("user");
String userId = userObj.getString("user_id");
String userName = userObj.getString("username");
User user = new User(userId, userName);
Message message = new Message();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createdAt);
message.setUser(user);
messageArrayList.add(message);
}
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, 1);
}
} else {
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
}
package com.webapp.chat.adapter;
/**
* Created by COMP on 17-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.webapp.chat.R;
import com.webapp.chat.model.Message;
public class ChatRoomThreadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static String TAG = ChatRoomThreadAdapter.class.getSimpleName();
private String userId;
private int SELF = 100;
private static String today;
private Context mContext;
private ArrayList<Message> messageArrayList;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView message, timestamp;
public ViewHolder(View view) {
super(view);
message = (TextView) itemView.findViewById(R.id.message);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
}
}
public ChatRoomThreadAdapter(Context mContext, ArrayList<Message> messageArrayList, String userId) {
this.mContext = mContext;
this.messageArrayList = messageArrayList;
this.userId = userId;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
// view type is to identify where to render the chat message
// left or right
if (viewType == SELF) {
// self message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_self, parent, false);
} else {
// others message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_other, parent, false);
}
return new ViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if (message.getUser().getId().equals(userId)) {
return SELF;
}
return position;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Message message = messageArrayList.get(position);
((ViewHolder) holder).message.setText(message.getMessage());
String timestamp = getTimeStamp(message.getCreatedAt());
if (message.getUser().getName() != null)
timestamp = message.getUser().getName() + ", " + timestamp;
((ViewHolder) holder).timestamp.setText(timestamp);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
}
Set setReverseLayout=true so that LayoutManager will layout items from end.
Something like this:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(layoutManager);
EDIT: This will reverse the data order but not scroll the RecyclerView to the last item. For keeping data order same and simply scrolling the RecyclerView to the last item set setStackFromEnd=true
Sample:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
Use RecyclerView LayoutManager to scroll item at position
recyclerView.getLayoutManager().scrollToPosition(messageList.size()-1);
And u are good to go
LinearLayoutManager manager = new LinearLayoutManager(ActivityMessage.this);
manager.setStackFromEnd(true);
manager.setReverseLayout(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);
Related
I have problem with Spinner. I download data from API using Volley and put it into Spinner. I can see all items that I get from API. However I can not select it, also spinner setOnItemSelectedListener does not fire (no logs, no toasts).
Logs from getDataFromAPI() works great, all data is correctly downloaded from source.
You can see code below.
Thanks for help.
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
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.Volley;
import com.example.plantapp.Model.WeatherStation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class StationUser extends AppCompatActivity {
private Spinner stationUserSpinnerStation, stationUserSpinnerConfirm;
private String IMGW_URL = "https://danepubliczne.imgw.pl/api/data/synop";
private ArrayList<WeatherStation> WeatherList = new ArrayList<>();
private List<String> StationList = new ArrayList<>();
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station_user);
stationUserSpinnerStation = findViewById(R.id.stationUserSpinnerStation);
mQueue = Volley.newRequestQueue(this);
getDataFromAPI();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, StationList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stationUserSpinnerStation.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
stationUserSpinnerStation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spinnerValue = parent.getItemAtPosition(position).toString();
stationUserSpinnerStation.setSelection(position);
Log.d("saodjawduiaw", spinnerValue + " " + position + " " + id + "\n\n");
Toast.makeText(StationUser.this,
"Selected item" + spinnerValue,
Toast.LENGTH_SHORT).show();
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(StationUser.this,
"Selected item",
Toast.LENGTH_SHORT).show();
}
});
}
private void getDataFromAPI() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, IMGW_URL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject station = response.getJSONObject(i);
String stacja = station.getString("stacja");
double temperatura = station.getDouble("temperatura");
double suma_opadu = station.getDouble("suma_opadu");
WeatherStation tempstation = new WeatherStation(stacja, temperatura, suma_opadu);
WeatherList.add(tempstation);
StationList.add(stacja);
Log.d("info", stacja + " " + temperatura + " " + suma_opadu + "\n\n");
Log.d("stacja", tempstation.getStation() + tempstation.getTemperature() + tempstation.getRainfall());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
try it like this, define arrayadapter as global variable then initialize arrayadapter inside onCreate method, then Call arrayAdapter.notifyDataSetChanged(); inside onResponse method
public class StationUser extends AppCompatActivity {
private Spinner stationUserSpinnerStation, stationUserSpinnerConfirm;
private String IMGW_URL = "https://danepubliczne.imgw.pl/api/data/synop";
private ArrayList<WeatherStation> WeatherList = new ArrayList<>();
private List<String> StationList = new ArrayList<>();
private RequestQueue mQueue;
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
stationUserSpinnerStation = findViewById(R.id.stationUserSpinnerStation);
mQueue = Volley.newRequestQueue(this);
getDataFromAPI();
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, StationList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stationUserSpinnerStation.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
stationUserSpinnerStation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spinnerValue = parent.getItemAtPosition(position).toString();
stationUserSpinnerStation.setSelection(position);
Log.d("saodjawduiaw", spinnerValue + " " + position + " " + id + "\n\n");
Toast.makeText(getApplicationContext(),
"Selected item" + spinnerValue,
Toast.LENGTH_SHORT).show();
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(),
"Selected item",
Toast.LENGTH_SHORT).show();
}
});
}
private void getDataFromAPI() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, IMGW_URL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject station = response.getJSONObject(i);
String stacja = station.getString("stacja");
double temperatura = station.getDouble("temperatura");
double suma_opadu = station.getDouble("suma_opadu");
WeatherStation tempstation = new WeatherStation(stacja, temperatura, suma_opadu);
WeatherList.add(tempstation);
StationList.add(stacja);
Log.d("info", stacja + " " + temperatura + " " + suma_opadu + "\n\n");
Log.d("stacja", tempstation.getData1() + tempstation.getData2() + tempstation.getData3());
arrayAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
Im trying to trigger an event when i return to an activity hitting the back button.
what i want to do is when i go back with the backbutton reload some items. Is there any way to do this?
here is my Main Activity where i want to do the "reload" of data, Some thing like "onResume" or "onReEnter"
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ActivityTemporadaJson extends AppCompatActivity {
private String Nombre;
private int IdTmdb;
private String Tipo;
private int NumeroTemp;
private DBHelper mydb;
private ProgressDialog pDialog;
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original";
private Temporada temp;
private TextView nombrePelicula;
private ImageView fotoPortada;
private TextView sinopsis;
private TextView NumEpsVal;
private TextView fechaLanzVal;
private ArrayList<Episodio> episodios;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private RecyclerAdapterEpisodio mAdapterEp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temporada_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent recep = this.getIntent();
episodios = new ArrayList<>();
Nombre = recep.getStringExtra("Nombre");
Tipo = recep.getStringExtra("Tipo");
IdTmdb = Integer.parseInt(recep.getStringExtra("idSerie"));
NumeroTemp = Integer.parseInt(recep.getStringExtra("NumTemp"));
this.setTitle(Nombre);
nombrePelicula = (TextView) this.findViewById(R.id.NombrePelicula);
fotoPortada = (ImageView) this.findViewById(R.id.FotoPortada);
sinopsis = (TextView) this.findViewById(R.id.Sinopsis);
NumEpsVal = (TextView) this.findViewById(R.id.NumEpsVal);
fechaLanzVal = (TextView) this.findViewById(R.id.FechaLanzVal);
recyclerView = (RecyclerView) this.findViewById(R.id.recyclerviewEpisodios);
mydb = new DBHelper(this);
if (Tipo.equalsIgnoreCase("SQL")) {
Cursor res = mydb.getResultQuery("SELECT count(e.Visto) as numVisto FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp + " and e.visto = 1");
res.moveToFirst();
int NumVisto = res.getInt(0);
mydb.UpdateEpsVistos(NumVisto, IdTmdb, NumeroTemp);
TextView NumEpsVis = (TextView) this.findViewById(R.id.EpsVis);
TextView NumEpsVisVal = (TextView) this.findViewById(R.id.EpsVisVal);
NumEpsVis.setVisibility(View.VISIBLE);
NumEpsVisVal.setVisibility(View.VISIBLE);
AQuery androidAQuery = new AQuery(this);
res = mydb.getResultQuery("SELECT Nombre, Sinopsis, FechaInicio, Poster, NumeroEpisodios,EpisodiosVistos FROM Temporada WHERE IdTMDB = " + IdTmdb + " and NumeroTemporada = " + NumeroTemp);
res.moveToFirst();
nombrePelicula.setText(res.getString(0));
sinopsis.setText(res.getString(1));
fechaLanzVal.setText(res.getString(2));
androidAQuery.id(fotoPortada).image(res.getString(3), true, true, 150, 0);
NumEpsVal.setText(Integer.toString(res.getInt(4)));
NumEpsVisVal.setText(Integer.toString(res.getInt(5)));
Cursor resEps = mydb.getResultQuery("SELECT e.Nombre, e.NumeroEpisodio, e.NumeroTemporada, e.FechaEmision, e.Sinopsis, e.Poster, e.Visto, e.IdEpisodio FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp);
resEps.moveToFirst();
while (resEps.isAfterLast() == false) {
boolean visto = false;
if (resEps.getInt(6) == 1) {
visto = true;
}
Episodio nuevo = new Episodio(resEps.getInt(7), 0, resEps.getString(0), resEps.getInt(1), resEps.getInt(2), resEps.getString(3), resEps.getString(4), resEps.getString(5), visto);
episodios.add(nuevo);
resEps.moveToNext();
}
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(episodios, IdTmdb, Tipo);
recyclerView.setAdapter(mAdapterEp);
} else {
new GetTemp(this).execute();
}
//mydb = new DBHelper(this);
}
private class GetTemp extends AsyncTask<Void, Void, Void> {
Context c;
public GetTemp(Context c)
{
this.c = c;
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
//https://api.themoviedb.org/3/tv/57243/season/1?api_key=5e2780b2117b40f9e4dfb96572a7bc4d&language=en-US
String url = "https://api.themoviedb.org/3/tv/"+IdTmdb+"/season/"+NumeroTemp+"?api_key="+API+"&language=es-ES";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray episodes = jsonObj.getJSONArray("episodes");
String fecha = jsonObj.getString("air_date");
String nombreSerie = jsonObj.getString("name");
int numEps = episodes.length();
int numTemp = jsonObj.getInt("season_number");
String sinop = jsonObj.getString("overview");
String poster =URLFOTO + jsonObj.getString("poster_path");
// looping through All Contacts
for (int i = 0; i < episodes.length(); i++) {
JSONObject c = episodes.getJSONObject(i);
Episodio nuevo = new Episodio();
nuevo.setSinopsis(c.getString("overview"));
nuevo.setFechaEmision(c.getString("air_date"));
nuevo.setNombreEpisodio(c.getString("name"));
nuevo.setNumeroEpisodio(c.getInt("episode_number"));
nuevo.setNumeroTemporada(c.getInt("season_number"));
nuevo.setPoster(URLFOTO + c.getString("still_path"));
episodios.add(nuevo);
}
temp = new Temporada(0, IdTmdb, nombreSerie, sinop, fecha, poster, numTemp,false, 0, numEps, episodios);
} catch (final JSONException e) {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AQuery androidAQuery=new AQuery(c);
// Dismiss the progress dialog
if (pDialog.isShowing())
{
pDialog.dismiss();
}
androidAQuery.id(fotoPortada).image(temp.getPoster(), true, true, 150,0);
String Nombre = "Temporada " + temp.getNumeroTemporada();
nombrePelicula.setText(Nombre);
sinopsis.setText(temp.getSinopsis());
NumEpsVal.setText(Integer.toString(temp.getNumeroEpisodios()));
fechaLanzVal.setText(temp.getFechaInicio());
mLinearLayoutManager = new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(temp.getEpisodios(),IdTmdb,Tipo);
recyclerView.setAdapter(mAdapterEp);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(c);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
}
You can use onRestart , which will be triggered when existing activity will be bought back to front .
As quoted in docs
Called after onStop() when the current activity is being re-displayed
to the user (the user has navigated back to it). It will be followed
by onStart() and then onResume().
so Override onRestart
#Override
public void onRestart() {
// you come back to me
}
I want to count row wise total for each item according to its quantity.my problem is that i want to start increment in each row from 1 but if i do increment in first row for e.g. from 1 to 5 then in next row its start from 6 but I want it will start from 1.how I resolve this problem?
Code is:
OrderScreenActivity.java
package com.example.veer.quickpos.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
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.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.veer.quickpos.R;
import com.example.veer.quickpos.adapter.ListAdapter;
import com.example.veer.quickpos.adapter.ListItemAdapter;
import com.example.veer.quickpos.utility.Utils;
import com.example.veer.quickpos.utils.app.Constants;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Veer on 12/07/2016.
*/
public class OrderScreenActivity extends BaseActivity {
public static String CmpId, GroupID, GroupName, UnderGroupId, ParentGroupName,ItemID,ItemName,CategoryID,SellingPrice;
public static ArrayList<String> CmpIdList, GroupIDList, GroupNameList, UnderGroupIdList, ParentGroupNameList;
public static LinearLayout ll;
public EditText edtitem;
public ListView lstitem;
public ListView listItemqty;
public static String item;
ListAdapter adapter;
public int total;
ListItemAdapter adapter2;
public static ArrayList<String> nameList,priceLIst,ItemIDList,ItemNameList,CategoryIDList,SellingPriceList,qtyList;
ProgressDialog pDialog;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
lstitem = (ListView)findViewById(R.id.lstitem);
edtitem = (EditText)findViewById(R.id.edtitem);
listItemqty = (ListView)findViewById(R.id.listviewItem);
makeJsonStringRequest();
}
public void makeJsonStringRequest() {
String URL = Utils.BASE_URL + Utils.GET_GROUP + Utils.AUTH_KEY;
Log.e("URL =>", URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("Response", response);
JSONArray mResponse = new JSONArray(response);
CmpIdList = new ArrayList<String>();
GroupIDList = new ArrayList<String>();
GroupNameList = new ArrayList<String>();
UnderGroupIdList = new ArrayList<String>();
ParentGroupNameList = new ArrayList<String>();
if (mResponse.length() != 0) {
for (int i = 0; i < mResponse.length(); i++) {
JSONObject obj = mResponse.optJSONObject(i);
CmpId = obj.optString("CmpId");
GroupID = obj.optString("GroupID");
GroupName = obj.optString("GroupName");
UnderGroupId = obj.optString("UnderGroupId");
ParentGroupName = obj.optString("ParentGroupName");
Log.d("CmpId", "" + CmpId);
Log.d("GroupID", "" + GroupID);
Log.d("GroupName", "" + GroupName);
Log.d("UnderGroupId", "" + UnderGroupId);
Log.d("ParentGroupName", "" + ParentGroupName);
CmpIdList.add(CmpId);
GroupIDList.add(GroupID);
GroupNameList.add(GroupName);
UnderGroupIdList.add(UnderGroupId);
ParentGroupNameList.add(ParentGroupName);
/*GetGodowns getGodowns = new GetGodowns();
getGodowns.setGoDownId(_id);
getGodowns.setName(_name);
getGodowns.setDate(CurrentDate);
getGodowns.setSyncData(_Sync);
listGetGodowns.add(getGodowns);*/
}
for (int i = 0; i < CmpIdList.size(); i++) {
ll = (LinearLayout) findViewById(R.id.llgroup);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button txv = new Button(OrderScreenActivity.this);
txv.setWidth(290);
txv.setHeight(180);
txv.setTextColor(getResources().getColor(R.color.darksky));
txv.setText(GroupNameList.get(i));
ll.addView(txv);
txv.setTextSize(15);
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("in onclick:","");
item = edtitem.getText().toString();
Log.d("value of edittext text:",""+item);
makeJsonStringRequestItem(item);
}
});
Log.d("Id of textview :", "" + txv.getId());
}
//myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
hideProgress();
// myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
// hideProgress();
}
hideProgress();
Log.e(Constants.TAG, "GetTill response => " + mResponse.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgress();
Toast.makeText(OrderScreenActivity.this, "Error in fetching data, PLease try again", Toast.LENGTH_LONG).show();
Log.v("Error String Request", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
showProgress();
}
public void makeJsonStringRequestItem(String Item) {
Log.d("item group id in item api:",""+GroupID);
String URL = Utils.BASE_URL + Utils.GET_ITEMS + Utils.AUTH_KEY +"&ItemName="+ Item +"&GroupId=0";
Log.e("URL =>", URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("Response", response);
JSONArray mResponse = new JSONArray(response);
CmpIdList = new ArrayList<String>();
ItemIDList = new ArrayList<String>();
ItemNameList = new ArrayList<String>();
CategoryIDList = new ArrayList<String>();
SellingPriceList = new ArrayList<String>();
if (mResponse.length() != 0) {
for (int i = 0; i < mResponse.length(); i++) {
JSONObject obj = mResponse.optJSONObject(i);
CmpId = obj.optString("CmpId");
ItemID = obj.optString("ItemID");
ItemName = obj.optString("ItemName");
CategoryID = obj.optString("CategoryID");
SellingPrice = obj.optString("SellingPrice");
Log.d("CmpId", "" + CmpId);
Log.d("ItemID", "" + ItemID);
Log.d("ItemName", "" + ItemName);
Log.d("CategoryID", "" + CategoryID);
Log.d("SellingPrice", "" + SellingPrice);
CmpIdList.add(CmpId);
ItemIDList.add(ItemID);
ItemNameList.add(ItemName);
CategoryIDList.add(CategoryID);
SellingPriceList.add(SellingPrice);
/*GetGodowns getGodowns = new GetGodowns();
getGodowns.setGoDownId(_id);
getGodowns.setName(_name);
getGodowns.setDate(CurrentDate);
getGodowns.setSyncData(_Sync);
listGetGodowns.add(getGodowns);*/
}
Log.d("Itemnamelist value:",ItemNameList.toString());
Log.d("SellingPriceList value:",SellingPriceList.toString());
adapter = new ListAdapter(OrderScreenActivity.this,ItemNameList,SellingPriceList);
lstitem.setAdapter(adapter);
adapter2 = new ListItemAdapter(OrderScreenActivity.this,ItemNameList,SellingPriceList);
listItemqty.setAdapter(adapter2);
for (int i = 0; i < CmpIdList.size(); i++) {
ll = (LinearLayout) findViewById(R.id.llgroup);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button txv = new Button(OrderScreenActivity.this);
txv.setWidth(290);
txv.setHeight(180);
txv.setTextColor(getResources().getColor(R.color.darksky));
txv.setText(GroupNameList.get(i));
ll.addView(txv);
txv.setTextSize(15);
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Log.d("Id of textview :", "" + txv.getId());
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
hideProgress();
// myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
// hideProgress();
}
hideProgress();
Log.e(Constants.TAG, "Getgroup item response => " + mResponse.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgress();
Toast.makeText(OrderScreenActivity.this, "Error in fetching data, PLease try again", Toast.LENGTH_LONG).show();
Log.v("Error String Request", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
showProgress();
}
private void showProgress() {
pDialog = new ProgressDialog(OrderScreenActivity.this);
pDialog.setMessage("Wait a moment");
pDialog.setCancelable(false);
pDialog.show();
}
private void hideProgress() {
if (null != pDialog) {
pDialog.dismiss();
}
}
}
ListItemAdapter
package com.example.veer.quickpos.adapter;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.veer.quickpos.R;
import java.util.ArrayList;
public class ListItemAdapter extends BaseAdapter {
Activity context;
public ArrayList<String> NameList;
public ArrayList<String> PriceList;
public ArrayList<String> totalList;
public int flag;
public static int qty;
public static ArrayList<String> qtyList;
public int total,grandtotal;
public ListItemAdapter(Activity a, ArrayList<String> nameList,ArrayList<String> plist) {
this.context = a;
this.NameList = nameList;
this.PriceList = plist;
}
/*private view holder class*/
class ViewHolder {
public TextView txtname,txtprice,txttotal;
public TextView txtqty;
public Button btnplus, btnminus;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_item_qty, null);
holder = new ViewHolder();
holder.btnplus = (Button) convertView.findViewById(R.id.btnplus);
holder.btnplus.setTag(position);
holder.btnminus = (Button) convertView.findViewById(R.id.btnminus);
holder.txtname = (TextView) convertView.findViewById(R.id.item);
holder.txtqty = (TextView) convertView.findViewById(R.id.itemqty);
holder.txtqty.setTag(R.id.itemqty,position);
holder.txtprice = (TextView) convertView.findViewById(R.id.txtprice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
qtyList = new ArrayList<String>();
Log.d("Total row:",""+getCount());
Log.d("current position:",""+position);
Log.d("Item name at position:", "" + position + NameList.get(position));
holder.txtname.setText(NameList.get(position));
holder.txtprice.setText(PriceList.get(position));
holder.txtqty.setText(String.valueOf(flag));
// qty = Integer.parseInt(holder.txtqty.getText().toString());
// qtyList.add(String.valueOf(qty));
qty=1;
Log.d("value of qty before button plus click:",""+qty);
Log.d("value of flag before button plus click:",""+flag);
// final int pos=(Integer)convertView.getTag();
holder.btnplus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int total = 0;
flag = qty;
Log.d("value of flag in button plus :",""+flag);
int itempos = holder.txtqty.getId();
holder.txtqty.setText(String.valueOf(flag));
Log.d("value of textqty in button plus :",""+holder.txtqty.getText().toString());
int pos=(Integer)v.getTag();
total = total + (Integer.parseInt(PriceList.get(pos))* (Integer.parseInt(holder.txtqty.getText().toString())));
Log.d("value of total in button plus :",""+total);
flag++;
}
});
holder.btnminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qty>0) {
qty = qty - 1;
Log.d("Value of qty in minus button:", "" + qty);
holder.txtqty.setText(String.valueOf(qty));
total = total + (Integer.parseInt(PriceList.get(position)) * (qty));
Log.d("total is:", "" + total);
}
}
});
return convertView;
}
#Override
public int getCount() {
return NameList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
In adapter I did code for counter in btnplus click event.I want to set qty 1 in each row in textview txtqty and in each row increment start from 1 and according to quantity I will get total but if in first row i set qty 5 with increment from plus button in next it start from 6 but I want it start from 1 same as first row how I resolve it?
I'm trying to get all the user chats (created in my database) using an ArrayList and Recyclerview.Adapter but only first item from my ArrayList is being shown on my emulator screen.
Here's the corresponding code:
MainActivity:
package com.wipro.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.wipro.chat.R;
import com.wipro.chat.adapter.ChatRoomsAdapter;
import com.wipro.chat.app.Config;
import com.wipro.chat.app.EndPoints;
import com.wipro.chat.app.MyApplication;
import com.wipro.chat.gcm.GcmIntentService;
import com.wipro.chat.gcm.NotificationUtils;
import com.wipro.chat.helper.SimpleDividerItemDecoration;
import com.wipro.chat.model.ChatRoom;
import com.wipro.chat.model.Message;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private ArrayList<ChatRoom> chatRoomArrayList;
private ChatRoomsAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. If not logged in launch
* login activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() == null) {
launchLoginActivity();
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
/**
* Broadcast receiver calls in two scenarios
* 1. gcm registration is completed
* 2. when new push notification is received
* */
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
subscribeToGlobalTopic();
} else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
// gcm registration id is stored in our server's MySQL
Log.e(TAG, "GCM registration id is sent to our server");
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
handlePushNotification(intent);
}
}
};
chatRoomArrayList = new ArrayList<>();
mAdapter = new ChatRoomsAdapter(this, chatRoomArrayList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new ChatRoomsAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new ChatRoomsAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
// when chat is clicked, launch full chat thread activity
ChatRoom userChatRoom = chatRoomArrayList.get(position);
Intent intent = new Intent(MainActivity.this, ChatRoomActivity.class);
intent.putExtra("user_id", userChatRoom.getId());
intent.putExtra("name", userChatRoom.getName());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
/**
* Always check for google play services availability before
* proceeding further with GCM
* */
if (checkPlayServices()) {
registerGCM();
fetchChatRooms();
}
}
/**
* Handles new push notification
*/
private void handlePushNotification(Intent intent) {
/*int type = intent.getIntExtra("type", -1);
// if the push is of chat room message
// simply update the UI unread messages count
if (type == Config.PUSH_TYPE_CHATROOM) {
Message message = (Message) intent.getSerializableExtra("message");
String chatRoomId = intent.getStringExtra("chat_room_id");
if (message != null && chatRoomId != null) {
updateRow(chatRoomId, message);
}
} else if (type == Config.PUSH_TYPE_USER) {
// push belongs to user alone
// just showing the message in a toast
Message message = (Message) intent.getSerializableExtra("message");
Toast.makeText(getApplicationContext(), "New push: " + message.getMessage(), Toast.LENGTH_LONG).show();
}*/
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
updateRow(userChatRoomId, message);
}
}
/**
* Updates the chat list unread count and the last message
*/
private void updateRow(String chatRoomId, Message message) {
for (ChatRoom cr : chatRoomArrayList) {
if (cr.getId().equals(chatRoomId)) {
int index = chatRoomArrayList.indexOf(cr);
cr.setLastMessage(message.getMessage());
cr.setUnreadCount(cr.getUnreadCount() + 1);
chatRoomArrayList.remove(index);
chatRoomArrayList.add(index, cr);
break;
}
}
mAdapter.notifyDataSetChanged();
}
/**
* fetching the chat rooms by making http call
*/
private void fetchChatRooms() {
StringRequest strReq = new StringRequest(Request.Method.GET,
EndPoints.CHAT_ROOMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
JSONArray chatRoomsArray = obj.getJSONArray("chat_rooms");
for (int i = 0; i < chatRoomsArray.length(); i++) {
JSONObject chatRoomsObj = (JSONObject) chatRoomsArray.get(i);
ChatRoom cr = new ChatRoom();
cr.setId(chatRoomsObj.getString("user_id"));
cr.setName(chatRoomsObj.getString("name"));
cr.setLastMessage("");
cr.setUnreadCount(0);
cr.setTimestamp(chatRoomsObj.getString("created_at"));
chatRoomArrayList.add(cr);
}
} else {
// error in fetching chat rooms
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
mAdapter.notifyDataSetChanged();
// subscribing to all chat room topics
//subscribeToAllTopics();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
// subscribing to global topic
private void subscribeToGlobalTopic() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, Config.TOPIC_GLOBAL);
startService(intent);
}
// Subscribing to all chat room topics
// each topic name starts with `topic_` followed by the ID of the chat room
// Ex: topic_1, topic_2
/*private void subscribeToAllTopics() {
for (ChatRoom cr : chatRoomArrayList) {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, "topic_" + cr.getId());
startService(intent);
}
}*/
private void launchLoginActivity() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
// clearing the notification tray
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
// starting the service to register with GCM
private void registerGCM() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra("key", "register");
startService(intent);
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported. Google Play Services not installed!");
Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_logout:
MyApplication.getInstance().logout();
break;
}
return super.onOptionsItemSelected(menuItem);
}
}
ChatRoomsAdapter:
package com.wipro.chat.adapter;
/**
* Created by COMP on 16-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.wipro.chat.R;
import com.wipro.chat.model.ChatRoom;
public class ChatRoomsAdapter extends RecyclerView.Adapter<ChatRoomsAdapter.ViewHolder> {
private Context mContext;
private ArrayList<ChatRoom> chatRoomArrayList;
private static String today;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name, message, timestamp, count;
public ViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
message = (TextView) view.findViewById(R.id.message);
timestamp = (TextView) view.findViewById(R.id.timestamp);
count = (TextView) view.findViewById(R.id.count);
}
}
public ChatRoomsAdapter(Context mContext, ArrayList<ChatRoom> chatRoomArrayList) {
this.mContext = mContext;
this.chatRoomArrayList = chatRoomArrayList;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_rooms_list_row, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ChatRoom chatRoom = chatRoomArrayList.get(position);
holder.name.setText(chatRoom.getName());
holder.message.setText(chatRoom.getLastMessage());
if (chatRoom.getUnreadCount() > 0) {
holder.count.setText(String.valueOf(chatRoom.getUnreadCount()));
holder.count.setVisibility(View.VISIBLE);
} else {
holder.count.setVisibility(View.GONE);
}
holder.timestamp.setText(getTimeStamp(chatRoom.getTimestamp()));
}
#Override
public int getItemCount() {
return chatRoomArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ChatRoomsAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ChatRoomsAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
PHP code which is retrieving the chatroom is like:
/* * *
* fetching all chat rooms
*/
$app->get('/chat_rooms', function() {
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllChats();
$response["error"] = false;
$response["chat_rooms"] = array();
// pushing single chat room into array
while ($chat_room = $result->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $chat_room["user_id"];
$tmp["name"] = $chat_room["name"];
$tmp["created_at"] = $chat_room["created_at"];
array_push($response["chat_rooms"], $tmp);
}
echoRespnse(200, $response);
});
public function getAllChats() {
$stmt = $this->conn->prepare("SELECT user_id, name, created_at FROM users");
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
There are two user chats in my database, namely Messaging, Chat and I'm getting the both from database into ArrayList but it is only showing Messaging.
Adapter display:
Response from database:
Check recycler_view in your main layout. The height should be set to "wrap_content".
I have following activities to load products from backend. Its a online food ordering with integration of paypal. I tried it in another app its working fine.
I am getting Error on onCreate Method.
There are three activities Item list , Product and product list adapter. I am getting error while loading view. When i commented the lines of adapter its not crashing but after adding the adapters its crashing . Its driving me crazy.
import com.flavorbaba.AppController;
import com.flavorbaba.Config;
import com.flavorbaba.Product;
import com.flavorbaba.ProductListAdapter;
import com.flavorbaba.ProductListAdapter.ProductListAdapterListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
public class ItemsList extends Activity implements ProductListAdapterListener {
private static final String TAG = ItemsList.class.getSimpleName();
private ListView listView;
private Button btnCheckout;
// To store all the products
private List<Product> productsList;
// To store the products those are added to cart
private List<PayPalItem> productsInCart = new ArrayList<PayPalItem>();
private ProductListAdapter adapter;
// Progress dialog
private ProgressDialog pDialog;
private static final int REQUEST_CODE_PAYMENT = 1;
// PayPal configuration
private static PayPalConfiguration paypalConfig = new PayPalConfiguration()
.environment(Config.PAYPAL_ENVIRONMENT).clientId(
Config.PAYPAL_CLIENT_ID);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_menu);
listView = (ListView) findViewById(R.id.list);
btnCheckout = (Button) findViewById(R.id.checkout);
productsList = new ArrayList<Product>();
adapter = new ProductListAdapter(ItemsList.this, productsList, this);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Starting PayPal service
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
startService(intent);
// Checkout button click listener
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check for empty cart
if (productsInCart.size() > 0) {
launchPayPalPayment();
} else {
Toast.makeText(getApplicationContext(),
"Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
// Fetching products from server
fetchProducts();
}
/**
* Fetching the products from our server
* */
private void fetchProducts() {
// Showing progress dialog before making request
pDialog.setMessage("Fetching products...");
showpDialog();
// Making json object request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Config.URL_PRODUCTS, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray products = response
.getJSONArray("products");
// looping through all product nodes and storing
// them in array list
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("p_id");
String name = product.getString("p_name");
String description = product
.getString("p_desc");
String image = product.getString("p_image");
BigDecimal price = new BigDecimal(product
.getString("p_price"));
String sku = product.getString("p_status");
Product p = new Product(id, name, description,
image, price, sku);
productsList.add(p);
}
listView.setAdapter(adapter);
// notifying adapter about data changes, so that the
// list renders with new data
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Verifying the mobile payment on the server to avoid fraudulent payment
* */
private void verifyPaymentOnServer(final String paymentId,
final String payment_client) {
// Showing progress dialog before making request
pDialog.setMessage("Verifying payment...");
showpDialog();
StringRequest verifyReq = new StringRequest(Method.POST,
Config.URL_VERIFY_PAYMENT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "verify payment: " + response.toString());
try {
JSONObject res = new JSONObject(response);
boolean error = res.getBoolean("error");
String message = res.getString("message");
// user error boolean flag to check for errors
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
if (!error) {
// empty the cart
productsInCart.clear();
}
} catch (JSONException e) {
e.printStackTrace();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Verify Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hiding the progress dialog
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("paymentId", paymentId);
params.put("paymentClientJson", payment_client);
return params;
}
};
// Setting timeout to volley request as verification request takes
// sometime
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
verifyReq.setRetryPolicy(policy);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(verifyReq);
}
/**
* Preparing final cart amount that needs to be sent to PayPal for payment
* */
private PayPalPayment prepareFinalCart() {
PayPalItem[] items = new PayPalItem[productsInCart.size()];
items = productsInCart.toArray(items);
// Total amount
BigDecimal subtotal = PayPalItem.getItemTotal(items);
// If you have shipping cost, add it here
BigDecimal shipping = new BigDecimal("0.0");
// If you have tax, add it here
BigDecimal tax = new BigDecimal("0.0");
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(
shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(
amount,
Config.DEFAULT_CURRENCY,
"Description about transaction. This will be displayed to the user.",
Config.PAYMENT_INTENT);
payment.items(items).paymentDetails(paymentDetails);
// Custom field like invoice_number etc.,
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
/**
* Launching PalPay payment activity to complete the payment
* */
private void launchPayPalPayment() {
PayPalPayment thingsToBuy = prepareFinalCart();
Intent intent = new Intent(ItemsList.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingsToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
/**
* Receiving the PalPay payment response
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.e(TAG, confirm.toJSONObject().toString(4));
Log.e(TAG, confirm.getPayment().toJSONObject()
.toString(4));
String paymentId = confirm.toJSONObject()
.getJSONObject("response").getString("id");
String payment_client = confirm.getPayment()
.toJSONObject().toString();
Log.e(TAG, "paymentId: " + paymentId
+ ", payment_json: " + payment_client);
// Now verify the payment on the server side
verifyPaymentOnServer(paymentId, payment_client);
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ",
e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e(TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.e(TAG,
"An invalid Payment or PayPalConfiguration was submitted.");
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onAddToCartPressed(Product product) {
PayPalItem item = new PayPalItem(product.getname(), 1,
product.getprice(), Config.DEFAULT_CURRENCY, product.getsku());
productsInCart.add(item);
Toast.makeText(getApplicationContext(),
item.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
--------------------------------------------------------------------------
import java.math.BigDecimal;
public class Product {
private String id, name, description, image, sku;
private BigDecimal price;
public Product() {
}
public Product(String id, String name, String description, String image,
BigDecimal price, String sku) {
this.id = id;
this.name = name;
this.description = description;
this.image = image;
this.price = price;
this.sku = sku;
}
public String getid() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getimage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public BigDecimal getprice() {
return price;
}
public String getsku() {
return sku;
}
}
---------------------------------------------------------------
package com.flavorbaba;
import com.flavorbaba.R;
import com.flavorbaba.AppController;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ProductListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Product> products;
private ProductListAdapterListener listener;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ProductListAdapter(Activity activity, List<Product> feedItems,
ProductListAdapterListener listener) {
this.activity = activity;
this.products = feedItems;
this.listener = listener;
}
#Override
public int getCount() {
return products.size();
}
#Override
public Object getItem(int location) {
return products.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item_product, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.productName);
TextView description = (TextView) convertView
.findViewById(R.id.productDescription);
TextView price = (TextView) convertView.findViewById(R.id.productPrice);
NetworkImageView image = (NetworkImageView) convertView
.findViewById(R.id.productImage);
Button btnAddToCart = (Button) convertView
.findViewById(R.id.btnAddToCart);
final Product product = products.get(position);
name.setText(product.getname());
description.setText(product.getdescription());
price.setText("Price: $" + product.getprice());
// user profile pic
image.setImageUrl(product.getimage(), imageLoader);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onAddToCartPressed(product);
}
});
return convertView;
}
public interface ProductListAdapterListener {
public void onAddToCartPressed(Product product);
}
}
This is a lot ta code dude...
I Wonder why your Productlistadapter object needs two contexts and why you give the first context as Item activity.this but nevertheless
One big Problem here is that you are trying to make a network connection on the main thread...that's an error when you are in strict mode while debugging...