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);
}
}
Related
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!
I am new to android development and I started working on an expandable RecyclerView. Now My problem is that my child (sub-modules) list is populated dynamically from the selected parent (Module) on the expandable RecyclerView. I tried using a for loop but only the last child list is populated when I open. I was just wondering if there is a way I could implement an item click listener to just return the single selected module.
Here is my adapter:
public class ReportAdapter extends ExpandableRecyclerViewAdapter<ModuleViewHolder, DoiViewHolder> {
Context context;
public ReportAdapter(List<? extends ExpandableGroup> groups, Context context) {
super(groups);
this.context = context;
}
#Override
public ModuleViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_module,parent,false);
return new ModuleViewHolder(view);
}
#Override
public DoiViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_doi,parent,false);
return new DoiViewHolder(view);
}
#Override
public void onBindChildViewHolder(DoiViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
ModuleDoi moduleDoi =(ModuleDoi) group.getItems().get(childIndex);
holder.setDoiName(moduleDoi.getName());
}
#Override
public void onBindGroupViewHolder(ModuleViewHolder holder, int flatPosition, ExpandableGroup group) {
holder.setModuleName(group.getTitle());
}
}
Here is my Parent Holder:
public class ModuleViewHolder extends GroupViewHolder implements View.OnClickListener{
TextView moduleName ;
public ModuleViewHolder(View itemView) {
super(itemView);
moduleName = (TextView) itemView.findViewById(R.id.module_name);
}
public void setModuleName(String name){
moduleName.setText(name);
}
}
Here is my Childs holder (Sub Modules)
public class DoiViewHolder extends ChildViewHolder {
TextView doiName;
public DoiViewHolder(View itemView) {
super(itemView);
doiName = (TextView) itemView.findViewById(R.id.module_doi_name);
}
public void setDoiName(String name){
doiName.setText(name);
}
}
Here is where I set the adapter. I am using the
moduleDoiList = fetchModuleMenus(APPID, MODULENAME);
fetch the submodules list from a json file. the app id in this case is a constant and the MODULENAME is obtained from the Modules Array list.
JSONArray jsonArray = jsonObject.getJSONArray("RESPONSE");
moduleDoiList = new ArrayList<>();
appModulesList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject eachModuleObject = jsonArray.getJSONObject(i);
MODULES modules = new MODULES(eachModuleObject.getString("MODULENAME"),
eachModuleObject.getString("MODULEID"));
ModulesList.add(modules);
for(int j = 0; j<ModulesList.size(); j++) {
String moduleTitle = ModulesList.get(i).getModuleName();
String MODULENAME = ModulesList.get(i).getModuleName();
moduleDoiList = fetchModuleMenus(APPID, MODULENAME);
appModulesList.add(new AppModules(moduleTitle, moduleDoiList));
}
}
reportAdapter = new ReportAdapter(appModulesList, POIDocsReportsActivity.this);
reportAdapter.notifyDataSetChanged();
rv.setAdapter(reportAdapter);
This is my fetchModulesMenu method:
public List<ModuleDoi> fetchModuleMenus(final String appId, final String moduleId) {
moduleDoiList = new ArrayList<>();
Thread thread = new Thread() {
Handler handler = new Handler();
ProgressDialog progressDialog;
boolean error;
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(POIDocsReportsActivity.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
String url = AppConfig.SERVER_URL + "load_module_menus.php";
HashMap hashMap = new HashMap();
hashMap.put("APPID", appId);
hashMap.put("MODULEID", moduleId);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, new JSONObject(hashMap), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response.toString());
error = jsonObject.getBoolean("ERROR");
if (error){
Toast.makeText(POIDocsReportsActivity.this, "MENUS NOT FOUND ", Toast.LENGTH_LONG).show();
}
else{
JSONArray jsonArray = jsonObject.getJSONArray("RESPONSE");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject eachMenu = jsonArray.getJSONObject(i);
ModuleDoi moduleDoi = new ModuleDoi(eachMenu.getString("POINAME"), eachMenu.getString("POICODE"));
moduleDoiList.add(moduleDoi);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(POIDocsReportsActivity.this, "CONNECTION ERROR ", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(POIDocsReportsActivity.this, "NO RESPONSE", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
};
thread.run();
return moduleDoiList;
}
I am using the Thoughtbot Custom Expandable Recycler View
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.
I have problem to set data into listview. Problem occurs after set message, message is set first after come 8th message from thread.
**below is my whole code :****(Here is my "Activity and adapter")**
public class Inboxreadmsg extends ActionBarActivity {
// <strong>Here is my global variable</strong>
ListView lv;
Handler h;
Custom_Inbox_Adapter ccAdpt;
Custom_Inbox_Adapter inadapter;
Runnable checker;
List<Dataset> dataset;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.messagesublistlayout);
// map id from layout</strong>
lv =(ListView)findViewById(R.id.readmessagelist);
/*****************************call thread of webservice with database****************************/
runThread();
startHandler();
/*****************************call thread of webservice with database****************************/
}
public void runThread()
{
h=new Handler();
checker=new Runnable()
{
#Override
public void run() {
// call webservice for fetch data
forthread();
h.postDelayed(checker,15000);
}
};
}
public void forthread()
{
// call webservice to fetch data
new InboxReadChat(null, InboxReadChat.TotalMessagesOfSingleSenderUser.geturl( recipientid,InAppUserid), InboxReadChat.TYPE_GET, InboxReadChat.TYPE_RECEIVE_MESSAGE_INBOX, new ServiceHitListenerInboxChat() {
#Override
public void onSuccess(Object Result, int id)
{
// After success of webservice response come this function
callFxnInSuccess(Result);
}
#Override
public void onError(String Error, int id)
{
// AfterError of webservice response come this function
// By this fxn set data from local database to listview
DBvaluesSet();
}
});
}
private void callFxnInSuccess(Object Result) {
dataset = new ArrayList<Dataset>();
String message="",alldatetime="",time="",date="",type="";
InboxDeliveredModel ibx=(InboxDeliveredModel) Result;
if(ibx.getTotalMessagesOfSingleSenderUser().size()>0)
{
// here webservice response data will add on local database
dbObject.Open();
for(int i=0;i<ibx.getTotalMessagesOfSingleSenderUser().size();i++)
{
message =ibx.getTotalMessagesOfSingleSenderUser().get(i).getMessage();
.....
dbObject.InboxMessageAll(message,InAppUsermobile,time,recipientid,type,date);
}
dbObject.close();
// After add data into database call below fxn to fetch data from database and set data in listview with adapter
try
{
DBvaluesSet();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void DBvaluesSet() {
dataset = new ArrayList<Dataset>();
try
{
// By this code fetch data from local database
Cursor c;
dbObject.Open();
c=dbObject.getallmessages(recipientid);
int countRow = c.getCount();
int counter = 0;
while(c.moveToNext())
{
msgboxitem = c.getString(0);
// number = c.getString(1);
timeitem = c.getString(2);
typeitem = c.getString(4);
datedbitem = c.getString(5);
try {
dataset.add(db.new Dataset(datedbitem, msgboxitem, timeitem, typeitem));
} catch (Exception e) {
e.printStackTrace();
}
}
dbObject.close();
// by below set data into listview into adapter
lv.setAdapter(ccAdpt=new Custom_Inbox_Adapter( getApplicationContext(),dataset,R.layout.row));
ccAdpt.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Here my adapter coding...
public class Custom_Inbox_Adapter extends BaseAdapter{
private Context gContext;
private List<Dataset> gData;
private int rEsource;
public Custom_Inbox_Adapter(Context cnt, List<Dataset> data ,int resource){
this.gData = data;
this.gContext = cnt;
this.rEsource = resource;
}
#Override
public int getCount() {
return gData.size();
}
#Override
public Dataset getItem(int position) {
return gData.get(position);
}
#Override
public long getItemId(int position) {> return gData.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) gContext.getSystemService(gContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(rEsource, null);
TextView txtReceiveMsg = (TextView) convertView.findViewById(R.id.ReceiveMsg);
TextView txtReceiveTime = (TextView) convertView.findViewById(R.id.ReceiveTime);
TextView txtSendMsg = (TextView) convertView.findViewById(R.id.sendMsg);
TextView txtSendTime = (TextView) convertView.findViewById(R.id.senttime);
TextView date = (TextView) convertView.findViewById(R.id.date);
// layout text chat
RelativeLayout relSend = (RelativeLayout) convertView.findViewById(R.id.LinearReceive);
RelativeLayout relreceive = (RelativeLayout) convertView.findViewById(R.id.LinearSend);
// layout date chat
RelativeLayout LinearDATE= (RelativeLayout) convertView.findViewById(R.id.LinearDATE);
if(position == 0){
fetchdata= gData.get(position).getDate().trim();
date.setText(fetchdata);
}
else{
fetchdata = gData.get(position).getDate().trim();
dd = gData.get((position-1)).getDate().trim();
if(fetchdata.equalsIgnoreCase(dd))
{
LinearDATE.setVisibility(View.GONE);
}
else
{
LinearDATE.setVisibility(View.VISIBLE);
Log.w("INBOX READ", "INBOX_READ_ADAPTER::::(date for position '1'):"+fetchdata);
date.setText(fetchdata);
}
}
relreceive.setVisibility(View.GONE);
relSend.setVisibility(View.VISIBLE);
//txtReceiveNumber.setText(number);
txtReceiveMsg.setText(cutmsg);
txtReceiveTime.setText(time);
}
return convertView;
}
}
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" />