I am working on this chat application. In that, I want to search particular message in recycler view. For that, I am using Filterable interface. When I try to update my arraylist with notifydatasetchange(), it is not changing the arraylist items. It remains as it is.
Here is my Adapter code.
MessageAdapter.java
package com.android.customizedchat;
import java.lang.*;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.BaseAdapter;
import android.widget.ArrayAdapter;
import android.app.Activity;
import android.content.Context;
import android.widget.Filter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.*;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> implements Filterable {
List<Message> filteredmessageList;
List<Message> messages;
public MessageAdapter(List<Message> objects){
this.messages = objects;
this.filteredmessageList = objects;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Message message = messages.get(position);
boolean myMsg=message.getIsMe();
setAlingnment(holder,myMsg);
holder.message.setText(message.getText());
holder.user.setText(message.getName());
holder.timestamp.setText(message.getTimestamp());
System.out.println("From Holder: "+holder.message.getText());
}
public void setAlingnment(ViewHolder holder,boolean isMe){
if(!isMe){
holder.message.setGravity(Gravity.LEFT);
holder.user.setGravity(Gravity.LEFT);
holder.timestamp.setGravity(Gravity.LEFT);
}else {
holder.message.setGravity(Gravity.RIGHT);
holder.user.setGravity(Gravity.RIGHT);
holder.timestamp.setGravity(Gravity.RIGHT);
}
}
#Override
public int getItemCount() {
return messages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView message;
public TextView user;
public TextView timestamp;
public ImageView message_image;
public ViewHolder(View view){
super(view);
message = (TextView) view.findViewById(R.id.messageTextView);
user = (TextView)view.findViewById(R.id.nameTextView);
timestamp = (TextView) view.findViewById(R.id.messageTimeStamp);
message_image = (ImageView) view.findViewById(R.id.messageImageView);
}
}
public Filter getFilter(){
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
System.out.println("Enter Filtering");
String charString = constraint.toString();
if(charString.isEmpty()){
filteredmessageList = messages;
}
else{
List<Message> filterlist = new ArrayList<>();
for(Message row : messages){
if(row.getText().toLowerCase().contains(charString.toLowerCase())){
filterlist.add(row);
}
}
filteredmessageList = filterlist;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredmessageList;
System.out.println(filterResults.values.toString());
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredmessageList = (ArrayList<Message>) results.values;
for (int i = 0; i < filteredmessageList.size(); i++) {
System.out.println(filteredmessageList.get(i).getText());
}
// notifyDataSetChanged();
}
};
}
}
And here is my Main Activity File
MainActivity.java
package com.android.customizedchat;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.*;
import android.widget.*;
import android.support.v7.widget.SearchView;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import android.view.*;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
public RecyclerView messageListView;
public MessageAdapter messageAdapter;
public EditText messageEditText;
public Button messageSendButton;
String TimeStamp="";
public List<Message> message;
private Socket socket;{
try{
socket = IO.socket("http://192.168.137.1:3000");
// socket = IO.socket("https://customizedchat.herokuapp.com");
}
catch (URISyntaxException e){
throw new RuntimeException(e);
}
}
public String username;
//public String url_connect ="http://192.168.137.1/test/retrivemessage.php";
public String url_connect = "http://wallstreet.000webhostapp.com/retrivemessage.php";
//public String url_insert = "http://192.168.137.1/test/insertmessage.php";
public String url_insert = "http://wallstreet.000webhostapp.com/insertmessage.php";
public String uname,msgs,tstamp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
String GroupID = bundle.getString("GroupID");
final String GroupName = bundle.getString("GroupName");
Toast.makeText(this, "ID"+GroupID+"Name"+GroupName, Toast.LENGTH_SHORT).show();
setTitle(GroupName);
socket.connect();
socket.emit("subscribe",GroupName);
socket.on("newM",handleIncomingMessages);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",0);
username=pref.getString("uname",null);
messageListView=(RecyclerView)findViewById(R.id.messageListView);
messageListView.setLayoutManager(new LinearLayoutManager(this));
messageEditText=(EditText)findViewById(R.id.messageEditText);
messageSendButton=(Button)findViewById(R.id.messageSendButton);
message =new ArrayList<>();
messageAdapter=new MessageAdapter(message);
messageListView.setAdapter(messageAdapter);
messageSendButton.setEnabled(true);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_connect, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
String res = response;
JSONArray msgs = new JSONArray(res);
for(int i=0;i<msgs.length();i++){
JSONObject msg =(JSONObject) msgs.get(i);
String status = msg.getString("code");
if(status.equals("success")){
String mesg = msg.getString("Message");
String uname = msg.getString("Username");
String tstamp = msg.getString("TimeStamp");
Message message1 = new Message(mesg,uname,tstamp);
if(uname.equals(username))
message1.setMe(true);
addMessage(message1);
}
else{
Toast.makeText(MainActivity.this, "The table for this group has been created in database", Toast.LENGTH_SHORT).show();
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<String,String>();
params.put("grpname",GroupName);
return params;
}
};
Connection.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
messageSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(messageEditText.getText().toString().trim().equals(""))) {
// final String time = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());\
Date dt = new Date();
long time = dt.getTime();
if (android.text.format.DateFormat.is24HourFormat(MainActivity.this)) {
TimeStamp = new SimpleDateFormat("hh:mm a", Locale.US).format(new Date(time));
}
else{
TimeStamp = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
}
final String msg =messageEditText.getText().toString().trim();
Message message = new Message(msg, username,TimeStamp);
message.setMe(true);
StringRequest insert = new StringRequest(Request.Method.POST, url_insert, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<String,String>();
params.put("grpname",GroupName);
params.put("message",msg);
params.put("username",username);
params.put("timestamp",TimeStamp);
return params;
}
};
Connection.getInstance(getApplicationContext()).addToRequestQueue(insert);
String MESSAGGE = messageEditText.getText().toString().trim();
addMessage(message);
messageEditText.setText("");
try {
JSONObject object = new JSONObject();
object.put("message", MESSAGGE);
object.put("userid", username);
object.put("timestamp",TimeStamp);
object.put("room",GroupName);
socket.emit("newM", object);
} catch (JSONException e) {
e.printStackTrace();
}
}
else
Toast.makeText(MainActivity.this, "Enter text", Toast.LENGTH_SHORT).show();
}
});
}
//for handeling incoming messages
private Emitter.Listener handleIncomingMessages = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data=(JSONObject) args[0];
String message,uname,tstamp;
try {
message=data.getString("message").toString().trim();
uname = data.getString("uname").toString();
tstamp = data.getString("tstamp").toString();
//System.out.println("------------------------------------------------------"+uname+" : "+message);
Message msg=new Message(message,uname,tstamp);
msg.setMe(false);
addMessage(msg);
}catch (JSONException e){
return;
}
}
});
}
};
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
MenuItem item = menu.findItem(R.id.actionSearch);
//SearchView searchView = (SearchView) item.getActionView();
android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) item.getActionView();
searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
messageAdapter.getFilter().filter(newText);
messageAdapter.notifyDataSetChanged();
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
public String getUsername(){
return username;
}
public void addMessage(Message m){
message.add(m);
messageAdapter = new MessageAdapter(message);
messageAdapter.notifyItemInserted(0);
messageListView.scrollToPosition(messageAdapter.getItemCount()-1);
}
}
When I print the filtered values on the console, it prints perfect. But it doesn't update the list of the recycler view.
It will be really helpful if someone can get into this and help me find solution.
You must have to update the message list before notifying adapter, here in this method:
#Override
public boolean onQueryTextChange(String newText) {
messageAdapter.getFilter().filter(newText);
messageAdapter.notifyDataSetChanged();
return false;
}
Related
public class Constant {
public static final String FIREBASE_CHAT_URL="https://roadcaremap.firebaseio.com/";
public static final String CHILD_USERS="users";
public static final String CHILD_CHAT="chat";
public static final String KEY_SEND_USER="key_send_user";
public static final String CHILD_CONNECTION="connecttion";
public static final String CHILD_LATITUDE="latitude";
public static final String CHILD_LONGITUDE="longitude";
public static final String KEY_EMAIL="email";
public static final String KEY_ONLINE="online";
public static final String KEY_OFFLINE="offline";
public static final String KEY_CLOSE="key_close";
}
I'm new to android. Recently, I encountered a problem when running the application on my device. The app crashes and shows me an error on this line which I do not know how to solve. I've added the code and picture of the logcat. Any help would be much appreciated. The error is shown in this line.
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
package com.snapsofts.demogmap.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.client.AuthData;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.gson.Gson;
import com.snapsofts.demogmap.R;
import com.snapsofts.demogmap.Services.LocationService;
import com.snapsofts.demogmap.common.Constant;
import com.snapsofts.demogmap.object.User;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
private Firebase rootUrl;
private Firebase urlCurrenUser;
private Firebase urlAllUser;
private FirebaseAuth mAuth;
private Firebase.AuthStateListener mAuthStateListener;
private String currenUserId;
private String currenUserEmail;
private ArrayList<User> arrUser;
private AllUserAdapter allUserAdapter;
private ArrayList<String> arrStringEmail;
private ValueEventListener valueEventListenerUserConnected;
private User currenUser;
#BindView(R.id.btnLogout)
Button btnLogout;
#BindView(R.id.lvUser)
ListView lvUser;
#BindView(R.id.tvUsserName)
TextView tvUsserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MainActivity.this.startService(new Intent(MainActivity.this, LocationService.class));
arrStringEmail = new ArrayList<>();
arrUser = new ArrayList<User>();
allUserAdapter = new AllUserAdapter(MainActivity.this, 0, arrUser);
lvUser.setAdapter(allUserAdapter);
lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(MainActivity.this,MapsActivity.class);
User user=arrUser.get(position);
Gson gson=new Gson();
intent.putExtra(Constant.KEY_SEND_USER,gson.toJson(user).toString()+"---"+gson.toJson(currenUser).toString());
startActivity(intent);
mAuth = FirebaseAuth.getInstance();
}
});
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
mAuthStateListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
setAuthenticatedUser();
}
};
rootUrl.addAuthStateListener(mAuthStateListener);
}
private void setAuthenticatedUser () {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
currenUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
currenUserEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
getCurrenUser();
getAllUser();
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
public void getCurrenUser() {
urlCurrenUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
urlCurrenUser.addValueEventListener(valueEventListenerCurrenUser);
valueEventListenerUserConnected=rootUrl.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean connected = (Boolean) dataSnapshot.getValue();
if (connected) {
urlCurrenUser.child(Constant.CHILD_CONNECTION).setValue(Constant.KEY_ONLINE);
urlCurrenUser.child(Constant.CHILD_CONNECTION).onDisconnect().setValue(Constant.KEY_OFFLINE);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
private ValueEventListener valueEventListenerCurrenUser = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
tvUsserName.setText("Hello "+user.name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
public void getAllUser() {
urlAllUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS);
urlAllUser.addChildEventListener(childEventListenerAllUser);
}
private ChildEventListener childEventListenerAllUser = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
if (!dataSnapshot.getKey().equals(currenUserId)){
arrStringEmail.add(user.email);
arrUser.add(user);
allUserAdapter.notifyDataSetChanged();
}else {
currenUser=user;
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
if (!dataSnapshot.getKey().equals(currenUserId)){
User user = dataSnapshot.getValue(User.class);
int index = arrStringEmail.indexOf(user.email);
arrUser.set(index, user);
allUserAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
#Override
protected void onDestroy() {
super.onDestroy();
try {
rootUrl.removeAuthStateListener(mAuthStateListener);
} catch (Exception e) {
}
try {
urlCurrenUser.removeEventListener(valueEventListenerCurrenUser);
} catch (Exception e) {
}
try {
urlAllUser.removeEventListener(childEventListenerAllUser);
} catch (Exception e) {
}
try {
rootUrl.getRoot().child(".info/connected").removeEventListener(valueEventListenerUserConnected);
}catch (Exception e){}
}
#OnClick(R.id.btnLogout)
public void btnLogout() {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
stopService(new Intent(this, LocationService.class));
AuthUI.getInstance().signOut(this);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
}
public class AllUserAdapter extends ArrayAdapter<User> {
private Activity mActivity;
private ArrayList<User> mArrUser;
#BindView(R.id.tvNameUser)
TextView tvNameUser;
#BindView(R.id.tvStatus)
TextView tvStatus;
public AllUserAdapter(Activity mActivity, int resource, ArrayList<User> mArrUser) {
super(mActivity, resource, mArrUser);
this.mActivity = mActivity;
this.mArrUser = mArrUser;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = mActivity.getLayoutInflater();
convertView = layoutInflater.inflate(R.layout.item_list_user, null);
}
ButterKnife.bind(this, convertView);
tvNameUser.setText(mArrUser.get(position).name);
tvStatus.setText(mArrUser.get(position).connecttion);
if (mArrUser.get(position).connecttion.equals(Constant.KEY_ONLINE)){
tvStatus.setTextColor(Color.parseColor("#00FF00"));
}else {
tvStatus.setTextColor(Color.parseColor("#FF0000"));
}
return convertView;
}
}
}
logcat
I will encode user input into a single URL, I use Uri.encode but error response remains 400. how to make the encode work?
the result is that "space" is replaced with "%20" but the response still fails
And this is my code.,
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
Any help would be appreciated.
Modify your code like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
getJobs(""); //get your data as it is
OnQuerySubmit();
return view;
}
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
getJobs(query);
return false;
}
});
}
public void getJobs(final String query) {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, AppConfig.URL_GETJOBS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: " + response);
try {
JSONObject jsonObject=new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if (!error) {
jobList.clear();
JSONArray transaksiArray = jsonObject.JSONArray("transaksi");
....
....
....
jobList.add(job);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(Tag, error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
if(!TextUtils.isEmpty(query){
map.put("title", query);
}else{}
return map;
}
};
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
package com.mimdudin.carekkerje.Activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.mimdudin.carekkerje.Adapter.HomeRecyclerViewAdapter;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.AppConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static com.android.volley.VolleyLog.TAG;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private HomeRecyclerViewAdapter homeRecyclerViewAdapter;
private List<Job> jobList;
private RequestQueue queue;
private MaterialSearchView searchView;
private ProgressDialog progressDialog;
private SharedPreferences sharedPreferences;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
jobList = getJobs(AppConfig.URL_GETJOBS);
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
homeRecyclerViewAdapter.notifyDataSetChanged();
sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
OnQuerySubmit();
return view;
}
public void OnQuerySubmit(){
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
super.onCreateOptionsMenu(menu, inflater);
}
public void showDialog() {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
public void hideDialog(){
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
HomeRecyclerviewAdapter.java
package com.mimdudin.carekkerje.Adapter;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mimdudin.carekkerje.Activities.HomeFragment;
import com.mimdudin.carekkerje.Activities.HomeFragmentDetail;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import java.util.List;
/**
* Created by master on 12/12/17.
*/
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<HomeRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Job> jobList;
public HomeRecyclerViewAdapter(Context context, List<Job> jobs){
this.context = context;
jobList = jobs;
}
#Override
public HomeRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.home_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(HomeRecyclerViewAdapter.ViewHolder holder, int position) {
Job job = jobList.get(position);
holder.title.setText(job.getTitle());
holder.namaPerusahaan.setText(job.getNamaPerusahaan());
holder.kriteria_1.setText(job.getKriteria_1());
holder.kriteria_2.setText(job.getKriteria_2());
holder.kriteria_3.setText(job.getKriteria_3());
holder.gaji.setText(job.getGaji());
holder.lokasi.setText(job.getLokasi());
holder.tanggal.setText(job.getTanggal());
String img_logoLink = job.getImg_logo();
Glide.with(context)
.load(img_logoLink) // URL
.apply(new RequestOptions().placeholder(android.R.drawable.ic_dialog_info)
.error(android.R.drawable.ic_dialog_alert).centerCrop().dontAnimate()
// .centerCrop(), .crossFade(), .thumbnail(), .dontAnimate(), .dontTransform() BitmapTransformation(.circleCrop())
)
.into(holder.img_logo); //TARGET GAMBAR YANG NAK DIUBAH
}
#Override
public int getItemCount() {
return jobList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
TextView namaPerusahaan;
TextView lokasi;
TextView kriteria_1;
TextView kriteria_2;
TextView kriteria_3;
TextView gaji;
ImageView img_logo;
TextView tanggal;
public ViewHolder(final View itemView, final Context ctx) {
super(itemView);
context = ctx;
title = itemView.findViewById(R.id.titleID);
namaPerusahaan = itemView.findViewById(R.id.namaPerusahaanID);
kriteria_1 = itemView.findViewById(R.id.satuTv);
kriteria_2 = itemView.findViewById(R.id.duaTv);
kriteria_3 = itemView.findViewById(R.id.tigaTv);
gaji = itemView.findViewById(R.id.gajiID);
lokasi = itemView.findViewById(R.id.lokasiID);
img_logo = itemView.findViewById(R.id.img_logoID);
tanggal = itemView.findViewById(R.id.tanggalID);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HomeFragmentDetail fragmentDetail = new HomeFragmentDetail();
Bundle bundle = new Bundle();
Job job = jobList.get(getAdapterPosition());
bundle.putSerializable("job", job);
fragmentDetail.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
android.support.v4.app.FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.replace(R.id.frame_fragmenthome, fragmentDetail);
fragmentTransaction.commit();
//// Intent intent = new Intent(context, HomeDetailActivity.class);
//// intent.putExtra("job", job);
//// ctx.startActivity(intent);
}
});
}
}
}
HomeFragmentDetail.java
package com.mimdudin.carekkerje.Activities;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
*/
public class HomeFragmentDetail extends Fragment {
private TextView tvDeskripsi;
private TextView tvIndustri;
public HomeFragmentDetail() {
// Required empty public constructor
}
public static HomeFragmentDetail newInstance(){
HomeFragmentDetail homeFragmentDetail = new HomeFragmentDetail();
return homeFragmentDetail;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home_fragment_detail, container, false);
tvDeskripsi = view.findViewById(R.id.tvDeskripsi);
tvIndustri = view.findViewById(R.id.tvIndustri);
Bundle bundle = getArguments();
Job job = (Job) bundle.getSerializable("job");
String PostID = job.getId_post();
String titleID = job.getTitle();
tvDeskripsi.setText(PostID);
tvIndustri.setText(titleID);
return view;
// DataHolder dataholder=new DataHolder("1","TestName");
// Bundle bundle=new Bundle();
// bundle.putSerializable("obj",dataholder);
// Fragment fragment=new FragmentB();
// fragment.setArguments(bundle);
// fragmentManager = getActivity(). getSupportFragmentManager();
// fragmentTransaction = fragmentManager .beginTransaction();
// fragmentTransaction.add(R.id.container, fragment);
// fragmentTransaction.commit();
//Job job = (Job) getIntent.getSerializableExtra("job");
// Bundle bundle = getArguments();
// Job job = (Job) bundle.getSerializable("job");
// String jobID = job.getId_post();
// String titleID = job.getTitle();
}
}
AppConfig.java
package com.mimdudin.carekkerje.Util;
/**
* Created by master on 10/12/17.
*/
public class AppConfig {
public static final String URL = "http://192.168.43.142/Carekkerje/v1";
public static final String URL_REGISTER = URL + "/daftarUser";
public static final String URL_LOGIN = URL + "/loginUser";
public static final String URL_GETJOBS = URL + "/seluruhLowongan/";
public static final String URL_GETJOBSS = URL + "/seluruhLowongan/:title";
}
here is my code for SelectedCategoryActivity.java
its showing error that ArrayList cannot be cast to com.panaceasoft.citiesdirectory.models.PCityData, while I used the same way in my other code
package com.panaceasoft.citiesdirectory.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.panaceasoft.citiesdirectory.Config;
import com.panaceasoft.citiesdirectory.GlobalData;
import com.panaceasoft.citiesdirectory.R;
import com.panaceasoft.citiesdirectory.adapters.CategoryAdapter;
//import com.panaceasoft.citiesdirectory.adapters.CategoryAdapter1;
//import com.panaceasoft.citiesdirectory.models.CategoryRowData;
import com.panaceasoft.citiesdirectory.adapters.CityAdapter;
import com.panaceasoft.citiesdirectory.listeners.ClickListener;
import com.panaceasoft.citiesdirectory.listeners.RecyclerTouchListener;
import com.panaceasoft.citiesdirectory.models.CategoryData;
import com.panaceasoft.citiesdirectory.models.CityRowData;
import com.panaceasoft.citiesdirectory.models.PCityData;
import com.panaceasoft.citiesdirectory.models.PItemData;
import com.panaceasoft.citiesdirectory.models.PSubCategoryData;
import com.panaceasoft.citiesdirectory.utilities.Utils;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dell on 04-Jul-16.
*/
public class SelectedCategoryActivity extends AppCompatActivity {
private ProgressDialog prgDialog;
private String jsonStatusSuccessString;
private CollapsingToolbarLayout collapsingToolbar;
private Toolbar toolbar;
private ImageView detailImage;
private TextView txtTitle;
private RecyclerView mRecyclerView;
private StaggeredGridLayoutManager mLayoutManager;
private CityAdapter mAdapter;
private List<PCityData> myDataset = new ArrayList<>();
private CityRowData info;
private int selectedCategoryID;
private int selectedCityID;
private CategoryData category;
private PCityData city;
private ArrayList<PCityData> cityArrayList ;
//private ArrayList<PCityData> cityArrayData ;
private ArrayList<PSubCategoryData> subCategoryArrayList ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_category);
initUI();
initData();
saveSelectedCategoryInfo(category);
bindData();
loadCityGrid();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_news, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_news) {
Utils.psLog("Open News Activity");
final Intent intent;
intent = new Intent(this, NewsListActivity.class);
intent.putExtra("selected_category_id", selectedCategoryID + "");
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.blank_anim, R.anim.left_to_right);
}
private void initUI() {
initToolbar();
initCollapsingToolbarLayout();
}
private void initCollapsingToolbarLayout(){
try {
collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
} catch (Exception e) {
Utils.psErrorLogE("Error in initCollapsingToolbarLayout.", e);
}
}
private void initToolbar() {
try {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(Utils.isAndroid_5_0()){
Utils.setMargins(toolbar, 0, -102, 0, 0);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitle("");
toolbar.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
} catch (Resources.NotFoundException e) {
Utils.psErrorLogE("Error in initToolbar.", e);
}
}
private void initData() {
try {
jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
requestData(Config.APP_API_URL + Config.GET_ALL);
detailImage = (ImageView) findViewById(R.id.detail_image);
category = GlobalData.categorydata;
//city = GlobalData.citydata;
selectedCategoryID = category.id;
//selectedCityID = city.id;
} catch (Exception e) {
Utils.psErrorLogE("Error in initData.", e);
}
}
private void bindData() {
try {
if(collapsingToolbar != null){
collapsingToolbar.setTitle(Utils.getSpannableString(category.name));
makeCollapsingToolbarLayoutLooksGood(collapsingToolbar);
}
Picasso.with(getApplicationContext()).load(Config.APP_IMAGES_URL + category.cover_image_file).into(detailImage);
} catch (Exception e) {
Utils.psErrorLogE("Error in bindData.", e);
}
}
private void requestData(String uri) {
JsonObjectRequest request = new JsonObjectRequest(uri,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
Utils.psLog("City Status >>>>>>>>>>>>>: " + status);
if (status.equals(jsonStatusSuccessString)) {
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
//cityArrayList = gson.fromJson(response.getString("data"), listType);
Utils.psLog("City Count >>>>>>>>>>>>>: " + cityArrayList.size());
updateGlobalCityList();
}
} catch (JSONException e) {
Utils.psErrorLogE("Error in loading City List.", e);
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
prgDialog.cancel();
Utils.psLog("Error: " + error.getMessage());
}
// #Override
});
RequestQueue queue = Volley.newRequestQueue(this.getApplicationContext());
queue.add(request);
}
private void updateGlobalCityList() {
GlobalData.cityDatas.clear();
for (PCityData cd : cityArrayList) {
GlobalData.cityDatas.add(cd);
}
}
public void loadCityGrid() {
try {
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CityAdapter(myDataset, mRecyclerView);
mRecyclerView.setAdapter(mAdapter);
//cityArrayList = category.cities;
// for (PCityData cd : cityArrayList) {
// subCategoryArrayList = cd.sub_categories;
// info = new CityRowData();
//info.setCityId(cd.id);
// info.setCityName(cd.name);
//info.setCityImage(cd.cover_image_file);
// myDataset.add(info);
// }
mAdapter.notifyItemInserted(myDataset.size());
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
onItemClicked(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
mRecyclerView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
} catch (Resources.NotFoundException e) {
Utils.psErrorLogE("Error in loadCityGrid.", e);
}
}
public void onItemClicked( int position){
final Intent intent;
intent = new Intent(this,SubCategoryActivity.class);
GlobalData.citydata = cityArrayList.get(position);
intent.putExtra("selected_city_index", position );
intent.putExtra("selected_category_id", selectedCategoryID);
intent.putExtra("selected_city_id", cityArrayList.get(0).id);
startActivity(intent);
overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
private void makeCollapsingToolbarLayoutLooksGood(CollapsingToolbarLayout collapsingToolbarLayout) {
try {
final Field field = collapsingToolbarLayout.getClass().getDeclaredField("mCollapsingTextHelper");
field.setAccessible(true);
final Object object = field.get(collapsingToolbarLayout);
final Field tpf = object.getClass().getDeclaredField("mTextPaint");
tpf.setAccessible(true);
((TextPaint) tpf.get(object)).setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
((TextPaint) tpf.get(object)).setColor(getResources().getColor(R.color.colorAccent));
} catch (Exception ignored) {
}
}
private void saveSelectedCategoryInfo(CategoryData ct) {
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("_id", ct.id);
editor.putString("_name", ct.name);
editor.putString("_cover_image", ct.cover_image_file);
// editor.putString("_address", ct.address);
// editor.putString("_city_region_lat", ct.lat);
// editor.putString("_city_region_lng", ct.lng);
editor.commit();
} catch (Exception e) {
Utils.psErrorLogE("Error in saveSelectedCategoryInfo.", e);
}
}
}
GlobalData.java
package com.panaceasoft.citiesdirectory;
import com.panaceasoft.citiesdirectory.models.CategoryData;
import com.panaceasoft.citiesdirectory.models.PCityData;
import com.panaceasoft.citiesdirectory.models.PItemData;
import java.util.ArrayList;
public class GlobalData {
public static PItemData itemData = null;
public static PCityData citydata = null;
public static CategoryData categorydata = null;
public static ArrayList<PCityData> cityDatas = new ArrayList<PCityData>();
public static ArrayList<CategoryData> categoryDatas = new ArrayList<CategoryData>();
}
PCityData.java
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class PCityData implements Parcelable {
public int id;
public String name;
public String description;
public String address;
public String lat;
public String lng;
public String added;
public int status;
public int item_count;
public int category_count;
public int sub_category_count;
public int follow_count;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public String cover_image_description;
// public ArrayList<PSubCategoryData> sub_categories;
protected PCityData(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
address = in.readString();
lat = in.readString();
lng = in.readString();
added = in.readString();
status = in.readInt();
item_count = in.readInt();
category_count = in.readInt();
sub_category_count = in.readInt();
follow_count = in.readInt();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
cover_image_description = in.readString();
// if (in.readByte() == 0x01) {
// sub_categories = new ArrayList<PSubCategoryData>();
// in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
// } else {
// sub_categories = null;
// }
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(address);
dest.writeString(lat);
dest.writeString(lng);
dest.writeString(added);
dest.writeInt(status);
dest.writeInt(item_count);
dest.writeInt(category_count);
dest.writeInt(sub_category_count);
dest.writeInt(follow_count);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
dest.writeString(cover_image_description);
//if (sub_categories == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeList(sub_categories);
// }
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
#Override
public PCityData createFromParcel(Parcel in) {
return new PCityData(in);
}
#Override
public PCityData[] newArray(int size) {
return new PCityData[size];
}
};
}
logcat
07-12 02:58:33.320 1797-1797/com.panaceasoft.citiesdirectory E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.panaceasoft.citiesdirectory, PID: 1797
java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.panaceasoft.citiesdirectory.models.PCityData
at com.panaceasoft.citiesdirectory.activities.SelectedCategoryActivity$2.onResponse(SelectedCategoryActivity.java:209)
at com.panaceasoft.citiesdirectory.activities.SelectedCategoryActivity$2.onResponse(SelectedCategoryActivity.java:199)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I think the below line contains error
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
I think you are trying to cast gson.fromJson(response.getString("data"), listType) to PCityData which is ArrayList
you are getting error on this line:
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
because:
gson.fromJson(response.getString("data"), listType);
this return a arraylist and it is not casting into your custom model
to fix this change your GlobalData.java class
public static PCityData citydata = null;
to
public static ArrayList<PCityData> citydata = null;
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
// Issue is here
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
Fix 1 : GlobalData.citydata should be of type List<PCityData>.
Fix 2 : Change like this GlobalData.citydata = (List<PCityData>) gson.fromJson(response.getString("data"), listType);
I want to receive the value of the variable Id from the listItem clicked and to pass it in the other activity.But I am not receiving anything in the variable.
Here is the attached code :
MainActivity.java
package com.example.hp.citysearchapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<City> cityList = new ArrayList<City>();
private ListView listView;
private static String url;
ImageView searchIcon;
String idGet;
String edittextSearch;
TextInputLayout searchLayout;
EditText search;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.city_listView);
searchLayout=(TextInputLayout)findViewById(R.id.input_layout_search);
search=(EditText)findViewById(R.id.input_search);
searchIcon=(ImageView)findViewById(R.id.imageView);
adapter = new CustomListAdapter(this,cityList);
searchIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edittextSearch=search.getText().toString();
Log.d("hello2", search.getText().toString());
adapter.notifyDataSetChanged();
url = "http://test.maheshwari.org/services/testwebservice.asmx/SuggestCity?tryValue="+edittextSearch;
parsingMethod();
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,CityDetailsActivity.class);
City city = cityList.get(position);
idGet=city.getId();
Log.d("dfjdkfj", idGet); //Not receiving anything ,here is the problem
intent.putExtra("gettingId",idGet);
startActivity(intent);
}
});
}
private void parsingMethod() {
Log.d("hello", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
City city = new City();
try {
city.setId(obj.getString("Id"));
city.setTitle(obj.getString("Title"));
city.setDescription(obj.getString("Description"));
city.setExv1(obj.getString("ExtraValue1"));
Log.d("hello",obj.getString("ExtraValue1"));
city.setExv2(obj.getString("ExtraValue2"));
city.setExv3(obj.getString("ExtraValue3"));
city.setExv4(obj.getString("ExtraValue4"));
city.setExv5(obj.getString("ExtraValue5"));
city.setExv6(obj.getString("ExtraValue6"));
city.setExv7(obj.getString("ExtraValue7"));
city.setExv8(obj.getString("ExtraValue8"));
city.setExv9(obj.getString("ExtraValue9"));
cityList.add(city);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
City.java
package com.example.hp.citysearchapp;
/**
* Created by hp on 22-03-2016.
*/
public class City {
String title,description,exv1,exv3,exv6,id,exv2,exv4,exv5,exv9,exv7,exv8;
public City(String title, String description, String id, String exv1, String exv3, String exv6,
String exv2, String exv4 , String exv5 , String exv7 , String exv8 , String exv9) {
this.title = title;
this.description=description;
this.id=id;
this.exv1=exv1;
this.exv2=exv2;
this.exv3=exv3;
this.exv4=exv4;
this.exv5=exv5;
this.exv6=exv6;
this.exv7=exv7;
this.exv8=exv8;
this.exv9=exv9;
}
public City() {
}
public String getId() {
return id;
}
public String getExv2() {
return exv2;
}
public String getExv4() {
return exv4;
}
public String getExv5() {
return exv5;
}
public String getExv7() {
return exv7;
}
public String getExv8() {
return exv8;
}
public String getExv9() {
return exv9;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getExv1() {
return exv1;
}
public String getExv3() {
return exv3;
}
public String getExv6() {
return exv6;
}
public void setId(String id) {
this.id = id;
}
public void setExv2(String exv2) {
this.exv2 = exv2;
}
public void setExv4(String exv4) {
this.exv4 = exv4;
}
public void setExv5(String exv5) {
this.exv5 = exv5;
}
public void setExv7(String exv7) {
this.exv7 = exv7;
}
public void setExv8(String exv8) {
this.exv8 = exv8;
}
public void setExv9(String exv9) {
this.exv9 = exv9;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setExv1(String exv1) {
this.exv1 = exv1;
}
public void setExv3(String exv3) {
this.exv3 = exv3;
}
public void setExv6(String exv6) {
this.exv6 = exv6;
}
}
Please modify your code a bit to achieve this --
You already have --
City city = cityList.get(position);
Now add this line to get Id from the ListItem clicked --
String Id = city.getExv3(); //Use one of your actual Getter methods accordingly.
Hope this helps!
Since I'm using a CustomAdapter for my list , I have to use the following code :
TextView textView = (TextView)view.findViewById(R.id.id); /*(R.id.id) is the id of the textview */
String gettingID=textView.getText().toString();
I have three classes one user list holds the list of user when each user is clicked it directs you to chat class which holds the chats activity. I also have the conversation list which holds a single conversation. The problem is the list view does not show previous chats stored in parse data base how can I load the previous chats to my list view.
package com.example.user.mycareerchat;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.example.user.mycareerchat.custom.CustomActivity;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseClassName;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
public class UserList extends CustomActivity {
private static final String EXTRADATA = null;
// Declare Variables
// the chat list
private ArrayList<ParseUser> uList =new ArrayList<ParseUser>();
// the parseruser
public static ParseUser user=new ParseUser();
/////////////
public static ArrayList names = new ArrayList<String>();
private String currentUserId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
updateUserStatus(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
updateUserStatus(false);
}
#Override
protected void onResume() {
super.onResume();
loadUserList();
}
private void loadUserList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
//don't include yourself
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, com.parse.ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
uList = new ArrayList<ParseUser>(userList);
}
final ListView list = (ListView)findViewById(R.id.list);
ArrayAdapter namesArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.chat_item, names);
list.setAdapter(namesArrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
// openConversation(names, i);
String name= names.get(i).toString();
startActivity(new Intent(UserList.this, Chat.class).putExtra(EXTRADATA, name));
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
private void updateUserStatus(boolean online) {
user.put("online", online);
user.saveEventually();
}
private class UserAdapter extends BaseAdapter {
#Override
public int getCount() {
return uList.size();
}
#Override
public ParseUser getItem(int arg0) {
return uList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View v, ViewGroup arg2) {
if(v!=null)
v=getLayoutInflater().inflate(R.layout.chat_item,null);
ParseUser c= getItem(pos);
TextView lbl = (TextView) v;
lbl.setText(c.getUsername());
lbl.setCompoundDrawablesWithIntrinsicBounds(c.getBoolean("online")? R.drawable.ic_online:
R.drawable.ic_offline,0,
R.drawable.arrow,0);
return v;
}
}
}
//Conversation Class
package com.example.user.mycareerchat.model;
import com.example.user.mycareerchat.UserList;
import java.util.Date;
/**
* Created by user on 26/Aug/2015.
*/
public class Conversation {
public static final int STATUS_SENDING =0;
public static final int STATUS_SENT =1;
public static final int STATUS_FAILED =2;
private int status = STATUS_SENT;
private Date date;
private String sender;
private String msg;
//instatiates new conversation
public Conversation(String msg,Date date,String sender) {
this.msg =msg;
this.date = date;
this.sender = sender;
}
//instatiates new conversation
// public Conversation() {
//
// }
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isSent(){
return UserList.user.getUsername().equals(sender);
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
//Chat class
package com.example.user.mycareerchat;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Telephony;
import android.text.InputType;
import android.text.format.DateUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.user.mycareerchat.custom.CustomActivity;
import com.example.user.mycareerchat.model.Conversation;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class represents single chat class message
*/
public class Chat extends CustomActivity {
private ArrayList<Conversation> convList;
private ChatAdapter adp;
private EditText txt;
private String buddy;
private Date lastMsgDate;
private boolean isRunning;
private static Handler handler;
private static final String EXTRA_DATA = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
convList = new ArrayList<Conversation>();
ListView list = (ListView) findViewById(R.id.listchat);
adp = new ChatAdapter();
list.setAdapter(adp);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setStackFromBottom(true);
txt = (EditText) findViewById(R.id.txt);
txt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
setTouchNClick(R.id.btnSend);
buddy = getIntent().getStringExtra(EXTRA_DATA);
// getActionBar().setTitle(buddy);
loadConversationList();
handler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
isRunning =true;
loadConversationList();
}
#Override
protected void onPause() {
super.onPause();
isRunning = false;
}
#Override
public void onClick(View v) {
super.onClick(v);
if(v.getId()== R.id.btnSend){
sendMessage();
}
}
private void sendMessage() {
if(txt.length()==0)
return;
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txt.getWindowToken(),0);
String s =txt.getText().toString();
final Conversation c = new Conversation(s, new Date(),UserList.user.getUsername());
c.setStatus(Conversation.STATUS_SENDING);
convList.add(c);
adp.notifyDataSetChanged();
txt.setText(null);
ParseObject po = new ParseObject("Chat");
po.put("sender",UserList.user.getUsername());
po.put("receiver",buddy);
po.put("message",s);
po.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
c.setStatus(Conversation.STATUS_SENT);
else
c.setStatus(Conversation.STATUS_FAILED);
adp.notifyDataSetChanged();
}
});
}
/*load the conversation list from parse server and save the data of the last message that will
* be used to load only new received messages*/
private void loadConversationList() {
//load all messsages
ParseQuery<ParseObject> q =ParseQuery.getQuery("Chat");
if(convList.size()==0){
ArrayList<String> al = new ArrayList<String>();
al.add(buddy);
al.add(ParseUser.getCurrentUser().getUsername());
q.whereContainedIn("sender", al);
q.whereContainedIn("receiver",al);
}
else{
//load only new received messages....
if(lastMsgDate!=null){
q.whereLessThan("createdAt",lastMsgDate);
q.whereEqualTo("sender", ParseUser.getCurrentUser().getUsername());
q.whereEqualTo("receiver",buddy);
adp.notifyDataSetChanged();
}
//load messages in the most recent order
q.orderByDescending("createdAt");
q.setLimit(30);
q.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> li, ParseException e) {
if(li != null && li.size() >0){
for (int i =li.size()-1;i>=0;i--){
ParseObject po = li.get(i);
Conversation c =new Conversation(po.getString("message"),po.getCreatedAt(),po.getString("sender"));
convList.add(c);
if(lastMsgDate == null || lastMsgDate.before(c.getDate()))
lastMsgDate = c.getDate();
adp.notifyDataSetChanged();
}
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isRunning)
loadConversationList();
}
},1000);
//
}
});
}
}
/*this class is the adapter class for chat listview. this adapter shows the sent and received messages
*in the list item*/
private class ChatAdapter extends BaseAdapter{
#Override
public int getCount() {
return convList.size();
}
#Override
public Conversation getItem(int arg0) {
return convList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View v, ViewGroup arg2) {
Conversation c = getItem(pos);
if(c.isSent())
v=getLayoutInflater().inflate(R.layout.chat_item_sent,null);
else
v=getLayoutInflater().inflate(R.layout.chat_item_rcv,null);
TextView lbl =(TextView) v.findViewById(R.id.lbl1);
lbl.setText(DateUtils.getRelativeDateTimeString(Chat.this,c.getDate().getTime (),DateUtils.SECOND_IN_MILLIS,DateUtils.DAY_IN_MILLIS,0));
lbl =(TextView) v.findViewById(R.id.lbl2);
lbl.setText(c.getMsg());
lbl =(TextView) v.findViewById(R.id.lbl3);
if (c.isSent()){
if (c.getStatus()==Conversation.STATUS_SENT)
lbl.setText("Delivered");
else if (c.getStatus()==Conversation.STATUS_SENDING)
lbl.setText("Sending...");
else
lbl.setText("Failed");
}
else
lbl.setText("");
return v;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}