Android App crashes when intent a new activity - java

I need help to find out why it wont go to the next activity (case R.id.Signin_Btn), I've got this issue in another Activity which was perfectly working before this class was made.
I've been through and checked everything and cant find a way to resolve this issue.
public class Login extends ActionBarActivity implements View.OnClickListener {
ArrayList<Driver> DriverArrayList;
DriverAdapter Dadapter;
ArrayList<Vehicle> VehicleArrayList;
VehicleAdapter Vadapter;
ArrayList<Plot> PlotArrayList;
PlotAdapter Padapter;
ImageButton Driver_Btn;
ImageButton Vehicle_Btn;
ImageButton Plot_Btn;
Button Signin_Btn;
private Intent myIntent;
private int DriverID = 0;
private int VehicleID = 0;
private int PlotID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Driver_Btn = (ImageButton) findViewById(R.id.Select_Driver);
Driver_Btn.setOnClickListener(this);
Vehicle_Btn = (ImageButton) findViewById(R.id.Select_Vehicle);
Vehicle_Btn.setOnClickListener(this);
Plot_Btn = (ImageButton) findViewById(R.id.Select_Plot);
Plot_Btn.setOnClickListener(this);
Signin_Btn = (Button) findViewById(R.id.Signin_Btn);
Signin_Btn.setOnClickListener(this);
//ArrayList
DriverArrayList = new ArrayList<Driver>();
VehicleArrayList = new ArrayList<Vehicle>();
PlotArrayList = new ArrayList<Plot>();
new JSONAsyncTask().execute("N/A");
ListView DlistView = (ListView) findViewById(R.id.DriverList);
ListView VlistView = (ListView) findViewById(R.id.VehicleList);
ListView PlistView = (ListView) findViewById(R.id.PlotList);
Dadapter = new DriverAdapter(getApplicationContext(), R.layout.driver_row, DriverArrayList);
Vadapter = new VehicleAdapter(getApplicationContext(), R.layout.vehicle_row, VehicleArrayList);
Padapter = new PlotAdapter(getApplicationContext(), R.layout.plot_row, PlotArrayList);
DlistView.setAdapter(Dadapter);
VlistView.setAdapter(Vadapter);
PlistView.setAdapter(Padapter);
Driver_Btn.setBackgroundColor(Color.GREEN);
DlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
DriverID = DriverArrayList.get(position).getID();
ResetButtonColours();
arg1.setSelected(true);
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
VlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
VehicleID = VehicleArrayList.get(position).getID();
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
PlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
PlotID = PlotArrayList.get(position).getID();
}
});
}
private void ResetButtonColours() {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
DriverListView.setVisibility(View.GONE);
VehicleListView.setVisibility(View.GONE);
PlotListView.setVisibility(View.GONE);
Driver_Btn.setBackgroundColor(Color.TRANSPARENT);
Vehicle_Btn.setBackgroundColor(Color.TRANSPARENT);
Plot_Btn.setBackgroundColor(Color.TRANSPARENT);
}
#Override
public void onClick(View v) {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
switch (v.getId()) {
case R.id.Select_Driver:
this.ResetButtonColours();
Driver_Btn.setBackgroundColor(Color.GREEN);
DriverListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Vehicle:
this.ResetButtonColours();
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Plot:
this.ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
break;
case R.id.Signin_Btn:
if (DriverID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Driver!", Toast.LENGTH_LONG).show();
} else if (VehicleID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Vehicle!", Toast.LENGTH_LONG).show();
} else if (PlotID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Plot!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Just a minute!", Toast.LENGTH_LONG).show();
myIntent = new Intent(this, Dashboard.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
break;
}
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Login.this);
dialog.setMessage("Loading, Please Wait");
dialog.setTitle("Connecting to Server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet HttpPost = new HttpGet(urls[0]);
HttpClient HttpClient = new DefaultHttpClient();
HttpResponse Response = HttpClient.execute(HttpPost);
int Status = Response.getStatusLine().getStatusCode();
//if (Status == 200) {
HttpEntity Entity = Response.getEntity();
String Data = EntityUtils.toString(Entity);
JSONObject Object = new JSONObject(Data);
JSONArray DriverArray = Object.getJSONArray("drivers");
for (int i = 0; i < DriverArray.length(); i++) {
JSONObject Current = DriverArray.getJSONObject(i);
Driver Driver = new Driver();
Driver.setID(Current.getInt("id"));
Driver.setName(Current.getString("name"));
DriverArrayList.add(Driver);
}
JSONArray VehicleArray = Object.getJSONArray("vehicles");
for (int i = 0; i < VehicleArray.length(); i++) {
JSONObject Current = VehicleArray.getJSONObject(i);
Vehicle Vehicle = new Vehicle();
Vehicle.setID(Current.getInt("id"));
Vehicle.setName(Current.getString("make") + ' ' + Current.getString("model"));
Vehicle.setReg("(" + Current.getString("reg") + ")");
VehicleArrayList.add(Vehicle);
}
JSONArray PlotArray = Object.getJSONArray("plots");
for (int i = 0; i < PlotArray.length(); i++) {
JSONObject Current = PlotArray.getJSONObject(i);
Plot Plot = new Plot();
Plot.setID(Current.getInt("id"));
Plot.setName(Current.getString("name"));
PlotArrayList.add(Plot);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Dadapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to Fetch Content from Server", Toast.LENGTH_LONG).show();
}
}
}
}

Have you added the new Activity to the manifest file?
Add this
<activity
android:name=".Dashboard"
android:label="Dashboard" />

Related

RecyclerView empty after data update

I am developing Android app which obtains information about restaurants from server and shows them in RecyclerView. When first package of information is obtained from server, everything works as expected, but, when I change search criteria and request new package of information from server, RecyclerView becomes blank. I used Toasts to debug what is coming from server and I am convinced that data is properly formatted. Also, variables that are used for accepting the data are also properly handled in code, according to my observations. Do you maybe know why my RecyclerView is empty when second package of data should be shown? Here is the code.
AfterLoginActivity.java
public class AfterLoginActivity extends AppCompatActivity {
/* interface main elements */
LinearLayout afterLoginLayout;
LinearLayout restaurantListLayout;
EditText restaurantEditText;
Button findRestaurantButton;
LoadingDialog loadingDialog;
AlphaAnimation loadingAnimation;
RecyclerView restaurantsRecyclerView;
int recycler_set = 0;
Button signOutButton;
GoogleSignInClient mGoogleSignInClient;
MyAdapter myAdapter = null;
/* server-client communication data */
public static String UploadUrl = "https://gdedakliknem.com/klopator.php";
public static String[] received;
String restaurants[] = new String[40];
String logos_as_strings[] = new String[40];
Bitmap logos[] = new Bitmap[40];
int num_of_elements = 0;
int data_received = 0;
/* user data */
String person_email;
String person_name;
String restaurant;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
/* interface main elements */
afterLoginLayout = findViewById(R.id.afterLoginLayout);
restaurantListLayout = findViewById(R.id.restaurantListLayout);
restaurantEditText = findViewById(R.id.restaurantEditText);
findRestaurantButton = findViewById(R.id.findRestaurantButton);
restaurantsRecyclerView = findViewById(R.id.restaurantsRecyclerView);
signOutButton = findViewById(R.id.signOutButton);
loadingAnimation = new AlphaAnimation(1F, 0.8F);
loadingDialog = new LoadingDialog(AfterLoginActivity.this);
/* UPDATING INTERFACE ELEMENTS */
/* execution thread */
final Handler handler = new Handler();
final int delay = 2000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
/* check if recycler view is set */
if(recycler_set == 0){
/* if not, check if there is data to fil it with */
if(data_received == 1){
/* convert received strings to images */
for(int i = 0; i < num_of_elements; i++){
logos[i] = stringToBitmap(logos_as_strings[i]);
}
/* fill interface elements */
loadingDialog.dismissDialog();
myAdapter = new MyAdapter(AfterLoginActivity.this, restaurants, logos, num_of_elements);
restaurantsRecyclerView.setAdapter(myAdapter);
restaurantsRecyclerView.setLayoutManager(new LinearLayoutManager(AfterLoginActivity.this));
afterLoginLayout.setVisibility(View.GONE);
restaurantListLayout.setVisibility(View.VISIBLE);
recycler_set = 1;
}
}
handler.postDelayed(this, delay);
}
}, delay);
/* catch restaurant name from user's entry */
findRestaurantButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restaurant = restaurantEditText.getText().toString();
if(!restaurant.isEmpty()){
view.startAnimation(loadingAnimation);
loadingDialog.startLoadingDialog();
sendRequest();
} else{
Toast.makeText(AfterLoginActivity.this, "Unesite naziv restorana!", Toast.LENGTH_LONG).show();
}
}
});
/* enable signing out */
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.signOutButton:
signOut();
break;
}
}
});
/* obtaining email */
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
person_email = acct.getEmail();
person_name = acct.getDisplayName();
}
}
#Override
public void onBackPressed() {
afterLoginLayout.setVisibility(View.VISIBLE);
restaurantsRecyclerView.setVisibility(View.GONE);
data_received = 0;
recycler_set = 0;
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AfterLoginActivity.this, "Signed out", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if (Response.equals("Restaurant not found")){
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Uneti restoran ne postoji u sistemu! Proverite da li ste dobro napisali naziv", Toast.LENGTH_LONG).show();
} else{
received = Response.split(";");
if (received.length > 0){
data_received = 1;
num_of_elements = received.length / 2;
//Toast.makeText(getApplicationContext(), "num of elements: " + num_of_elements, Toast.LENGTH_LONG).show();
for(int i = 0; i < num_of_elements; i++){
logos_as_strings[i] = received[i*2];
restaurants[i] = received[i*2+1];
//Toast.makeText(getApplicationContext(), "restaurants: " + restaurants, Toast.LENGTH_LONG).show();
}
} else{
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Greška u prijemu", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(final VolleyError error) {
//volleyError = error;
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Toast.makeText(getApplicationContext(), "get params", Toast.LENGTH_LONG).show();
Map<String, String> params = new HashMap<>();
params.put("control", "find_restaurant");
params.put("restaurant", restaurant);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AfterLoginActivity.this);
requestQueue.add(stringRequest);
}
public static Bitmap stringToBitmap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
} catch (Exception e) {
e.getMessage();
return null;
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
String restaurants[];
Bitmap logos[];
Context context;
int num_of_elements;
public MyAdapter(Context ct, String rests[], Bitmap lgs[], int num){
context = ct;
restaurants = rests;
logos = lgs;
num_of_elements = num;
Toast.makeText(context, Integer.toString(restaurants.length), Toast.LENGTH_LONG).show();
for(int i = 0; i < restaurants.length; i++){
Toast.makeText(context, restaurants[i], Toast.LENGTH_SHORT).show();
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.restaurant_item_layout, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
holder.restaurantNameTextView.setText(restaurants[position]);
holder.restaurantLogoImageView.setImageBitmap(logos[position]);
holder.restaurantItemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AfterPickingRestaurantActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
logos[position].compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("byteArray", bs.toByteArray());
intent.putExtra("picked_restaurant_name", restaurants[position]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
/*
int i = 0;
if (restaurants != null){
while(restaurants[i] != null){
i++;
}
} else{
i = restaurants.length;
}
return i;
*/
return num_of_elements;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView restaurantNameTextView;
ImageView restaurantLogoImageView;
LinearLayout restaurantItemLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
restaurantNameTextView = itemView.findViewById(R.id.restaurantNameTextView);
restaurantLogoImageView = itemView.findViewById(R.id.restaurantLogoImageView);
restaurantItemLayout = itemView.findViewById(R.id.restaurantItemLayout);
}
}
Add this lines after getting new data
myAdapter.notifyDataSetChanged()
Your Adapter Already set with RecyclerView in OnCreate Method.
so when'er you click on findRestaurantButton you just get Resturent data from server but collected data not pass in adapter so thats why to getting blank adapter..
Just put this line in your onResponse after set data in array..
myAdapter.notifyDataSetChanged()
I found out where is the mistake. If you take a look at the section where overriding of back button click is happening, I by mistake set to GONE recyclerView itself:
restaurantsRecyclerView.setVisibility(View.GONE);
instead of LinearLayout in which recyclerView is contained. Desired action was:
restaurantListLayout.setVisibility(View.GONE);
P.S. Everything works without calling notifyDataSetChanged(), I just create a new instance of myAdapater each time when I receive new data. I hope Garbage Collector is doing its job :)
Thanks everyone on help!

How to add new feed to recycleview at same time without scroll or refresh the view?

I have an activity in which I have used Recycle View to show all items as a list. On same activity I have given functionality to add new item. Everything is working fine. Items are adding in my database and its showing in list. I have added pagination on Recycle View it is also working fine. What I want that when user add new item at the same time when new data added to database but it is not updating in list. When user press back and again come on activity after that it is showing in list. I want to add add new item at same time without scroll the list or without go back.
TimelineActivity.java
public class TimelineActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private TimeLineListAdapter listAdapter;
private List<TimeLineItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
btnPost = (Button) findViewById(R.id.btnPost);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
buttonClickEvent();
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, "1");
}
});
}
}, 0, 2000);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
public void buttonClickEvent() {
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isInternetPresent) {
String text = txtStatusBox.getText().toString().trim();
if (!text.isEmpty()) {
if (thumbnail != null) {
String image = getStringImage(thumbnail);
JSONObject student2 = new JSONObject();
try {
student2.put("size", "1000");
student2.put("type", "image/jpeg");
student2.put("data", image);
} catch (JSONException e) {
e.printStackTrace();
}
addStory(text, token, String.valueOf(student2));
} else {
addStory(text, token, "");
}
} else {
Toast.makeText(TimelineActivity.this, "Please add some text or image.", Toast.LENGTH_SHORT).show();
}
} else {
final SweetAlertDialog alert = new SweetAlertDialog(TimelineActivity.this, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
imgImageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
/*fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialogFragment.show(getFragmentManager(), "MyDialogFragment");
//Toast.makeText(TimelineActivity.this, "Floating Button", Toast.LENGTH_SHORT).show();
}
});*/
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
TimeLineListAdapter.java
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
You have to notifiy dataset changed on listview when new feed is added so there are two things you can do :
Create a new TimeLineItem item when new feed is entered and add new item to it like this :
`
item.setStatus("New Status");
item.setProfilePic("New Profile Pic");
item.setTimeStamp("New TimeStamp");
item.setIsLike("True");
item.setTotalLikes("1000");
item.setTotalComment("2");
`
and then use timeLineItems.add(item) to add new item to ArrayList and call adapter.notifyDataSetChanged(); to get it in view .
2. Again create volley request and it will do it automatically but this is slower then above example.
If you have any query please ask .
You have to set this new list to the adapter.
You can create a setDataSet() method in your adapter and call it before notifydatasetchanged
Add below method in adapter
public void setDataSet(List<TimeLineItem> timeLineItems) {
this.timeLineItems = timeLineItems;
}
and call it before notifydatasetChanged like this:
adapter.setDataSet(timeLineItems);
adapter.notifyDataSetChanged();

Android studio, loading 2 spinners with different data from different MYSQL databases

My app has an itinerary function, the part where you create a new itinerary involves selecting from 2 spinners which drop down to present different options. The data coming from MQsql database and the JSON response is correct for both sets. Currently i have been able to get either one set of the data to load in the correct spinner (being which either just transport info or attraction info but not both), or i have been able to get both sets of data to load but both are displayed in the same 2 spinners. I need them to be separated into there allocated spinners but need help doing this as i dont undertand what im doing wrong.
createItinerary class:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
LayoutInflater myInflator;
View myView;
DBManager db;
myAdapter adapter;
String NAME;
String LOCATION;
String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
TextView TextTime;
String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
new GetTransport().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.go_home){
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
/*
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Entities.remove(position);
finalEntities.remove(position);
loadAttractions();
}
});*/
return myView;
}
}
}
Thank you to anyone who can help me with this.

runOnUiThread not updating listview

I think ive looked at almost all threads wont seem to work.
Ive got a chat and im trying to update the list view every second im doing it on another thread however, im using runOnUiThread though it still wont update im logging the return and it seems there is a return every second with the correct data.
The code
protected void onCreate(Bundle savedInstanceState) {
........
lv = (ListView) findViewById(R.id.message_array);
returnFunc = "messages";
messages();
send = (ImageButton) findViewById(R.id.sendMessage);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
returnFunc = "btnSend";
message = (EditText) findViewById(R.id.messageEditText);
message_input = message.getText().toString();
sendMessage();
}
});
new Thread(new Runnable() {
#Override
public void run() {
boolean test = true;
while (test) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
messages();
}
}
}).start();
}
public static Handler handler = new Handler();
public void messageLoop(){
handler.postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
messages();
handler.postDelayed(this,1000);
}
});
}
},1000);
}
the messages function which gets the data fine
public void messages() {
String urlParameters = String.format("%s", "chatid="+tempVars.chatID+"&token="+tempVars.token);
new AsyncHttpPost(this).execute("http://mylink.com/appAccess.php?action=messages&", urlParameters);
}
public void getMessages(String content){
myList = new ArrayList<Messages>();
int index = lv.getFirstVisiblePosition();
View v = lv.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - lv.getPaddingTop());
try{
JSONArray jsonarray = new JSONArray(content);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
boolean mine;
if(jsonobject.getString("isMine").equals("true")){
mine = true;
}else{
mine = false;
}
myList.add(new Messages(jsonobject.getString("message"),jsonobject.getString("timestamp"),jsonobject.getString("name"),mine,jsonobject.getString("id")));
}
}catch (Throwable tx){
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3)
{
Messages CurrentMessage = myList.get(position);
tempVars.messageID = CurrentMessage.getID();
//startActivity(new Intent("PersonalChat"));
}
});
if(arrayAdapter == null){
arrayAdapter = new CustomAdapter(this, myList);
}
lv = (ListView) findViewById(R.id.message_array);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
if(firstView == 0){
firstView = 1;
lv.setSelection(arrayAdapter.getCount() - 1);
}else{
lv.setSelectionFromTop(index, top);
}
}
class CustomAdapter
public class CustomAdapter extends ArrayAdapter<Messages>{
Messages currentMessage;
public CustomAdapter(Context context, ArrayList<Messages> messages){
super(context,R.layout.received_message, messages);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
currentMessage = myList.get(position);
setTitle(currentMessage.getName());
if(currentMessage.isMine()){
itemView = getLayoutInflater().inflate(R.layout.sent_message,parent, false);
TextView message = (TextView) itemView.findViewById(R.id.message);
message.setText(currentMessage.getMessage());
TextView timestamp = (TextView) itemView.findViewById(R.id.date);
timestamp.setText(currentMessage.getTimestamp());
}else{
itemView = getLayoutInflater().inflate(R.layout.received_message,parent, false);
TextView message = (TextView) itemView.findViewById(R.id.message_text);
message.setText(currentMessage.getMessage());
TextView timestamp = (TextView) itemView.findViewById(R.id.timestamp);
timestamp.setText(currentMessage.getTimestamp());
}
return itemView;
}
}
Thanks in advance
More info
When i call the message function originally in onCreate it works fine
new Thread(new Runnable() {
#Override
public void run() {
boolean test = true;
while (test) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}mymessage();
}
}
}).start();
Replace your getMessages() method with below code:
public void getMessages(String content){
myList = new ArrayList<Messages>();
int index = lv.getFirstVisiblePosition();
View v = lv.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - lv.getPaddingTop());
try{
JSONArray jsonarray = new JSONArray(content);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
boolean mine;
if(jsonobject.getString("isMine").equals("true")){
mine = true;
}else{
mine = false;
}
myList.add(new Messages(jsonobject.getString("message"),jsonobject.getString("timestamp"),jsonobject.getString("name"),mine,jsonobject.getString("id")));
}
arrayAdapter.notifyDataSetChanged();
}catch (Throwable tx){
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3)
{
Messages CurrentMessage = myList.get(position);
tempVars.messageID = CurrentMessage.getID();
//startActivity(new Intent("PersonalChat"));
}
});
if(arrayAdapter == null){
arrayAdapter = new CustomAdapter(this, myList);
}
lv = (ListView) findViewById(R.id.message_array);
lv.setAdapter(arrayAdapter);
if(firstView == 0){
firstView = 1;
lv.setSelection(arrayAdapter.getCount() - 1);
}else{
lv.setSelectionFromTop(index, top);
}
}

Custom Adapter with Search Not working

I tried to add textwatcher with filter class but it do not work plz help. I get the json array through the server using the url. the search(filter) doesnt work well.
public class CallDetails extends Activity {
SessionManager session;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
private List<Drivers> driverlist = null;
ListView listview;
ImageButton btback;
DriverAdapter dadapter;
String uid;
String name;
String email;
String odtyp;
static String oid;
Drivers driver;
private EditText editTextFilter;
private static String OUTBOX_URL ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calldetails);
Intent i = getIntent();
oid =i.getStringExtra("orderId");
odtyp =i.getStringExtra("ordertype");
OUTBOX_URL ="http://www.gdrive.com/api/calldetails.php?id="+oid;
//managing session...
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_EMAIL);
uid = user.get(SessionManager.KEY_UID);
btback =(ImageButton)findViewById(R.id.btnBack);
btback.setVisibility(View.INVISIBLE);
// Locate the EditText in listview_main.xml
editTextFilter = (EditText)findViewById(R.id.editTextFilter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editTextFilter.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3){ /* to do*/ }
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*to do*/ }
});
//populating view with data...
//driverList = new ArrayList<Drivers>();
new JSONAsyncTask().execute(OUTBOX_URL);
listview = (ListView)findViewById(R.id.drlist);
dadapter = new DriverAdapter(CallDetails.this, R.layout.list_item, driverList);
listview.setItemsCanFocus(false);
listview.setAdapter(dadapter);
//populating list ends
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), driverList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
public void back(View v){
Intent back = new Intent(getApplicationContext(), SafetyDrive.class);
startActivity(back);
finish();
}
private class DriverAdapter extends ArrayAdapter<Drivers> {
Context context;
int Resource;
LayoutInflater inflater;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
public DriverAdapter(Context context, int layoutResourceId,ArrayList<Drivers> drs) {
super(context, layoutResourceId, drs);
//inflater = ((Activity) context).getLayoutInflater();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = layoutResourceId;
driverList = drs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("in ", "view start");
View item = convertView;
DriverWrapper DriverWrapper = null;
if (item == null) {
DriverWrapper = new DriverWrapper();
item = inflater.inflate(Resource, null);
DriverWrapper.ename = (TextView) item.findViewById(R.id.textName);
DriverWrapper.ephone = (TextView) item.findViewById(R.id.textPhone);
DriverWrapper.mkcall = (ImageButton) item.findViewById(R.id.btnphone);
item.setTag(DriverWrapper);
} else {
DriverWrapper = (DriverWrapper) item.getTag();
}
Drivers driver = driverList.get(position);
DriverWrapper.ename.setText("Name: " + driver.getName());
DriverWrapper.ephone.setText("Phone: " + driver.getPhone());
final String dp = driver.getPhone().trim();
DriverWrapper.mkcall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//making call..
//Log.e("no is", dp);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +dp));
//callIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(callIntent);
//finish();
}
});
return item;
}
class DriverWrapper {
TextView ename;
TextView ephone;
ImageButton mkcall;
//ImageButton msg;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(driverList);
} else {
for (Drivers driver : driverList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
}
class JSONAsyncTask extends AsyncTask {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CallDetails.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//Log.d("in at-", "asynctask");
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("drivers");
if(jarray.length()!=0){
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Drivers driver = new Drivers();
driver.setPhone(object.getString("phone"));
driver.setName(object.getString("emp_name"));
driverList.add(driver);
}
}else{
driver = new Drivers();
driver.setPhone(" ");
driver.setName(" No Driver Place yet");
driverList.add(driver);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
btback.setVisibility(View.VISIBLE);
dadapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class Drivers {
private String name;
private String phone;
public Drivers() {
}
public Drivers(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
actually it wont filter because youve cleared the driverList and then in the else statement you loop to driverList which is already empty. the only thing you can do is create a backup list for the driversList and then use the backup list to get all data for filtering to the driverList.
Example Here:
// here is the backuplist
ArrayList<Drivers> backupList = new ArrayList<Drivers>();
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// actually its easy to just clear the backup list
// but due to reasons where users press backspace you have to load backup list only once
if(backupList.isEmpty()) {
backupList.addAll(driverList);
}
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(backupList);
} else {
for (Drivers driver : backupList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
Hope it helps :)

Categories