Data is not updating when using Volley Library in android - java

I am trying to get and send data by using Volley networking library. When I first Install my app the data is coming same which is in server and when I update it, it's running successfully but when I update it again the data is not going to the server and showing previous data. I checked lot's off tutorial or search about it but not find the result. So please can anyone help me to solve this error.
Below Class is for to get the data from server
public class ManageWebsiteActivity extends AppCompatActivity {
// Session Manager Class
UserSessionManager session;
String user_id, str_address, str_city, str_state, str_country, str_pincode;
TextView editBasicInfo, BusinessName, BusinessCategory;
private Toolbar toolbar;
TableRow businessAddress,contactInformation, businessHours, businessLogo, siteAppearance, photoGallery, customPage;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext() ,R.color.colorPrimary));
setContentView(R.layout.activity_manage_website);
//session manager
session = new UserSessionManager(getApplicationContext());
session.checkLogin();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
user_id = user.get(UserSessionManager.KEY_USER_ID);
editBasicInfo= (TextView)findViewById(R.id.textView3);
BusinessName= (TextView)findViewById(R.id.textView);
BusinessCategory= (TextView)findViewById(R.id.textView2);
businessAddress= (TableRow)findViewById(R.id.businessAddress);
contactInformation=(TableRow)findViewById(R.id.contactInformation);
businessHours= (TableRow)findViewById(R.id.businessHour);
businessLogo= (TableRow)findViewById(R.id.businessLogo);
siteAppearance= (TableRow)findViewById(R.id.siteAppearance);
photoGallery= (TableRow)findViewById(R.id.photoGallery);
customPage= (TableRow)findViewById(R.id.customPage);
getData();
businessAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent editIntent = new Intent(ManageWebsiteActivity.this,BusinessAddress.class);
editIntent.putExtra("str_address",str_address);
Log.e("add________",str_address);
editIntent.putExtra("str_city",str_city);
editIntent.putExtra("str_state",str_state);
editIntent.putExtra("str_country",str_country);
editIntent.putExtra("str_pincode",str_pincode);
startActivity(editIntent);
}
});
}
private void getData() {
String getBusinessAddressURL ="XYZ.php?username="+user_id;
StringRequest stringRequest = new StringRequest(Request.Method.POST,getBusinessAddressURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ManageWebsiteActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(ManageWebsiteActivity.this);
requestQueue.add(stringRequest);
}
public void showJSON(String response){
String str_address="";
String str_city="";
String str_state = "";
String str_country = "";
String str_pincode = "";
try {
JSONObject jsonObject = new JSONObject(response);
str_address = jsonObject.getString(Config.KEY_ADDRESS);
this.str_address=str_address;
str_city = jsonObject.getString(Config.KEY_CITY);
this.str_city=str_city;
str_state = jsonObject.getString(Config.KEY_STATE);
this.str_state=str_state;
str_country = jsonObject.getString(Config.KEY_COUNTRY);
this.str_country=str_country;
str_pincode = jsonObject.getString(Config.KEY_PINCODE);
this.str_pincode=str_pincode;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Below Class is for to Update the data from server
public class BusinessAddress extends AppCompatActivity {
public static final String KEY_ADDRESS = "address";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_COUNTRY = "country";
public static final String KEY_PIN = "pincode";
private EditText etAddress;
private EditText etCity;
private EditText etPin;
private EditText etState;
private EditText etCountry;
private Button buttonBusinessAddress;
private String user_id, str_address, str_city, str_state, str_country, str_pincode;
// Session Manager Class
UserSessionManager session;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_address);
getSupportActionBar().setTitle("Business Address");
//session manager
session = new UserSessionManager(getApplicationContext());
session.checkLogin();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
user_id = user.get(UserSessionManager.KEY_USER_ID);
etAddress = (EditText)findViewById(R.id.etAddress) ;
etCity = (EditText)findViewById(R.id.etCity) ;
etPin = (EditText)findViewById(R.id.etPin) ;
etState = (EditText)findViewById(R.id.etState) ;
etCountry = (EditText)findViewById(R.id.etCountry) ;
buttonBusinessAddress = (Button)findViewById(R.id.buttonBusinessAddress);
Bundle b = getIntent().getExtras();
if (b!=null){
str_address = b.getString("str_address");
str_city = b.getString("str_city");
str_state = b.getString("str_state");
str_country = b.getString("str_country");
str_pincode = b.getString("str_pincode");
}
etAddress.setText(str_address);
etCity.setText(str_city);
etState.setText(str_state);
etCountry.setText(str_country);
etPin.setText(str_pincode);
buttonBusinessAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData();
}
});
}
private void sendData() {
String UPDATE_URL = "XYZ.php?username="+user_id;
Log.e("URL_________________",UPDATE_URL);
final String str_address = etAddress.getText().toString().trim();
final String str_city = etCity.getText().toString().trim();
final String str_state = etState.getText().toString().trim();
final String str_country = etCountry.getText().toString().trim();
final String str_pin = etPin.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPDATE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equalsIgnoreCase("success")){
Log.e("send response________",response) ;
Toast.makeText(BusinessAddress.this, "Business Address has been updated", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(BusinessAddress.this, "Something Wrong" , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(BusinessAddress.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_ADDRESS, str_address);
params.put(KEY_CITY, str_city);
params.put(KEY_STATE, str_state);
params.put(KEY_COUNTRY, str_country);
params.put(KEY_PIN, str_pin);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(BusinessAddress.this);
requestQueue.add(stringRequest);
}
}

There is a problem in Cache so I used requestQueue.getCache().clear(); and solved it.

Related

Android login working only with the last member of list

private String usernameApi;
private String passwordApi;
private EditText usernameet;
private EditText passwordet;
private Button login_btn;
private List<User> users = new ArrayList<User>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameet = findViewById(R.id.username_etext);
passwordet = findViewById(R.id.password_etext);
login_btn = findViewById(R.id.login_btn);
getRetrofitArray();
}
Method for getting JSONArray from Restful service
void getRetrofitArray() {
String BASE_URL =
"http://192.168.0.18:8080/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RestAPI service = retrofit.create(RestAPI.class);
Call<JsonArray> jsonCall = service.getUsers();
jsonCall.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
String userData = response.body().toString();
Log.i("onResponse", userData);
Type listType = new TypeToken<List<User>>() {}.getType();
List<User> users = new Gson().fromJson(userData, listType);
Log.i("onResponse", users.toString());
for(int i = 0; i < users.size(); i++) {
usernameApi = users.get(i).getUsername();
passwordApi = users.get(i).getPassword();
}
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login(usernameet.getText().toString(), passwordet.getText().toString());
}
});
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
}
});
}
and finally the login method
public void login(String usernameInput, String passwordInput) {
if ((usernameInput.equals(usernameApi)) && (passwordInput.equals(passwordApi))) {
Intent i = new Intent(this, PostsActivity.class);
startActivity(i);
finish();
}else{
login_btn.setEnabled(false);
}
}
userData from response is [{"id":1,"name":"Radovan","username":"1","password":"1","photo":"slika"},
{"id":2,"name":"Milovan","username":"2","password":"2","photo":"slika"},
{"id":3,"name":"Zivan","username":"3","password":"3","photo":"slika"}]
Define this variable:
private List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
And try this code:
private String usernameApi;
private String passwordApi;
private EditText usernameet;
private EditText passwordet;
private Button login_btn;
private List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameet = findViewById(R.id.username_etext);
passwordet = findViewById(R.id.password_etext);
login_btn = findViewById(R.id.login_btn);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login(usernameet.getText().toString(), passwordet.getText().toString());
}
});
getRetrofitArray();
}
And:
void getRetrofitArray() {
String BASE_URL = "http://192.168.0.18:8080/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RestAPI service = retrofit.create(RestAPI.class);
Call<JsonArray> jsonCall = service.getUsers();
jsonCall.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
String userData = response.body().toString();
listOfMaps = new ArrayList<Map<String, String>>();
JSONArray temp = new JSONArray(userData);
for (int i = 0; i < temp.length(); i++) {
JSONObject row = (JSONObject) temp.get(i);
int id = row.getInt("id");
String name = row.getString("name");
String username = row.getString("username");
String password = row.getString("password");
String photo = row.getString("photo");
HashMap<String, String> user_exist = new HashMap<String, String>();
user_exist.put("id",String.valueOf("id"));
user_exist.put("name",name);
user_exist.put("username",username);
user_exist.put("password",password);
user_exist.put("photo",photo);
listOfMaps.add(user_exist);
}
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
}
});
}
And function:
public void login(String usernameInput, String passwordInput) {
boolean exist = false;
try{
for(int i=0; i<= listOfMaps.size(); i++){
if(listOfMaps.get(i).get("username").equals(usernameInput) && listOfMaps.get(i).get("password").equals(passwordInput)){
exist = true;
// save in shared preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", listOfMaps.get(i).get("username"));
editor.putString("password", listOfMaps.get(i).get("password"));
editor.putString("id", listOfMaps.get(i).get("id") );
editor.putString("photo", listOfMaps.get(i).get("photo") );
editor.commit();
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}
if(exist){
Intent i = new Intent(this, PostsActivity.class);
startActivity(i);
finish();
}else {
login_btn.setEnabled(false);
}
}
And to retrieve data in other activity try this code in PostsActivity:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(PostsActivity.this);
String username = sp.getString("id_user", "");
String password = sp.getString("password", "");
String id = sp.getString("id", "");
String photo = sp.getString("photo", "");

How to get data of current id on recyclerview

How can i display this to Recyclerview? i already got the data of the id i want to display it on Recyclerview. i want to filter the data that depends on the current user.. btw i am using navigation drawer and it is on fragment.
this is the logcat.
i want to the data of the given id to recyclerview. but the problem is it wont display. please help.. thanks in advance here is my code.
this is the AdapterApartment
public class AdapterApartment extends RecyclerView.Adapter<AdapterApartment.ViewHolderApartment> {
private Context mCtx;
private ArrayList<Apartment> apartmentList = new ArrayList <>();
public AdapterApartment(Context mCtx, ArrayList <Apartment> apartmentList) {
this.mCtx = mCtx;
this.apartmentList = apartmentList;
}
#Override
public ViewHolderApartment onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_houses, null);
return new ViewHolderApartment(view);
}
#Override
public void onBindViewHolder(ViewHolderApartment holder, int position) {
Apartment apartment = apartmentList.get(position);
holder.category.setText(apartment.getCategory());
holder.apartmentname.setText(apartment.getApartmentname());
holder.price.setText(String.valueOf(apartment.getPrice()));
}
#Override
public int getItemCount() {
return apartmentList.size();
}
class ViewHolderApartment extends RecyclerView.ViewHolder {
TextView category, apartmentname, price;
public ViewHolderApartment(View itemView) {
super(itemView);
category = itemView.findViewById(R.id.textViewCategory);
apartmentname = itemView.findViewById(R.id.textName);
price = itemView.findViewById(R.id.textViewPrice);
}
}
}
private String url = Server.URL + "viewapartment.php";
private String url2 = Server.URL + "listapartment.php";
private ArrayList<Apartment> apartmentList = new ArrayList <>();
private AdapterApartment adapterApartment;
private RecyclerView recyclerView;
private String id;
private String username;
private int success;
TextView txt_id, txt_username;
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
String tag_json_obj = "json_obj_req";
ProgressDialog pDialog;
public static LandlordAddApartment newInstance(String id, String username) {
LandlordAddApartment fragment = new LandlordAddApartment();
Bundle args = new Bundle();
args.putString(TAG_ID, id);
args.putString(TAG_USERNAME, username);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (getArguments() != null) {
id = getArguments().getString(TAG_ID);
username = getArguments().getString(TAG_USERNAME);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.landlord_add_apartment, container, false);
txt_id = (TextView) v.findViewById(R.id.add_txt_id);
txt_id.setText(id);
txt_username = (TextView)v.findViewById(R.id.add_txt_username);
txt_username.setText(username);
checkUseriD(id);
recyclerView = (RecyclerView)v.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapterApartment= new AdapterApartment(getActivity(), apartmentList);
loadApartment();
recyclerView.setAdapter(adapterApartment);
FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddApartment.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
startActivity(intent);
}
});
return v;
}
protected boolean isNetworkConnected() {
try {
ConnectivityManager mConnectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
return (mNetworkInfo == null) ? false : true;
}catch (NullPointerException e){
return false;
}
}
private void checkUseriD(final String id) {
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("searching ...");
showDialog();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url, new Response.Listener <String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "get id Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
JSONArray array = new JSONArray(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
Log.e("Success", jObj.toString());
Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map <String, String> getParams() {
// Posting parameters to login url
Map <String, String> params = new HashMap <String, String>();
params.put("userID", id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest1, tag_json_obj);
}
private void loadApartment() {
String url;
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
*
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, url2, new Response.Listener <String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject apartment = array.getJSONObject(i);
apartmentList.add(new Apartment(
apartment.getInt("userID"),
apartment.getString("Category"),
apartment.getString("apartmentName"),
apartment.getString("price_month")));
}
//creating adapter object and setting it to recyclerview
AdapterApartment adapter = new
AdapterApartment(getContext(), apartmentList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
this is the php. i dont know if my json code format is wrong.
<?php
$server="localhost";
$user = "root";
$password= "";
$database= "albayboardinghouse";
$connect = mysql_connect($server, $user, $password) or die ("connect failed!");
mysql_select_db($database) or die ("Error!");
$userID = $_POST['userID'];
class emp{}
if (empty($userID)) {
$response = new emp();
$response->success = 0;
$response->message = "Error data";
die(json_encode($response));
} else {
$query = mysql_query("SELECT userID, Category, apartmentName, price_month FROM apartmentlocation WHERE userID = '".$userID."'");
$row = mysql_fetch_array($query);
if (!empty($row)) {
$response = new emp();
$response->success = 1;
$response->userID = $row["userID"];
$response->Category = $row['Category'];
$response->apartmentName = $row['apartmentName'];
$response->price_month = $row['price_month'];
die(json_encode($response));
}
else{
$response = new emp();
$response->success = 0;
$response->message = "Error getting Data";
die(json_encode($response));
}
}
?>
i think you need to filter the data in your recycler view. if thats the issue, there is inbuilt Filter method to filter the datas from inside recycler view adapter.
below is the code used to filter contacts using filter method...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = contactList;
} else {
List<Contact> filteredList = new ArrayList<>();
for (Contact row : contactList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<Contact>) filterResults.values;
// refresh the list with filtered data
notifyDataSetChanged();
}
};
}
just check above code and change according to your need, as i cannot correctly figure your issue.
Thank you. :)

Values duplicating when fetching data from database and displaying to ListView

Im new to Android Developement and currently working on an app that should give me the time between first time clicking a button and second time clicking the button and add it to a currently selected customer.
Current Status of App:
I established a connection to da mySql Database using Volley and a local webservice.
It works to insert my customers and time stamps to the table, but when loading times for a specific customer i get a strange result in one case. I tried debugging it but the app keeps crashing on debugging without a message. When not debugging it doesnt crash but shows weird data.
To the problem:
In my main activity called "ZeitErfassen" i have a button to get an overview of all customers display in a ListView.
I create the Listview with a custom ArrayAdapter because i want to pass my objects to the next Activity where my customers are displayed.
So onCreate of the overview of customers i create a new arraylist and fill it with all customers from my database. this list i pass to my customadapter and then set it as my adapter of the Listview.
Now, when i click on an item, i call a php script and pass the customer_id to the query to fetch all times from database where customer_id = customer_id.
Now the part where i get "strange" data...
1.(Source:ZeitErfassen;Destination:AddCustomer) I create a new customer,example xyz, in the app, data gets passed to the database.
2.(Source:ZeitErfassen;Destination:DisplayCustomer) I call my overview for all customers where the ListView is filled with data as described above. At the end ob the List I see the customer i just created,xyz.
3.Go back to Main Activity(ZeitErfassen)
4.(Source:ZeitErfassen;Destination:DisplayCustomer)I open the overview for all customers again, and it shows my last created user two times! so last entry, xyz, entry before last, xyz!
After that, i can open the view as many times as i want, the customer never gets duplicated again!
The debugger stopps after step 2.
Now when i click on the new customers, it calls the script to fetch the times by customer_id.
One of the xyz entrys display the correct times from database.
The second one, i just found out, display the times where customer_id="". In the database the value for "" is 0.
I have no clue where the second customer suddenly appears from and debugging didnt help me either -.-
When i close the app an open it again, there ist just one entry for the user that was visible twice before closing the app. It doesnt duplicate on opening view...
Here is my code..
Main Activity ZeitErfassen
public class ZeitErfassen extends AppCompatActivity {
public static LinkedList<Kunde> kunden = new LinkedList<Kunde>();
boolean running = false;
long startTime,endTime,totalTime;
private SharedPreferences app_preferences;
private SharedPreferences.Editor editor;
private TextView displayTime;
public Button startEndButton;
private ArrayAdapter<String> adapter;
private Spinner spinner;
public static Kunde selectedCustomer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zeit_erfassen);
//Einstellungen laden
app_preferences = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
startTime= app_preferences.getLong("startTime", 0);
endTime = app_preferences.getLong("endTime", 0);
running = app_preferences.getBoolean("running", false);
displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
startEndButton = (Button)findViewById(R.id.start_Timer);
startEndButton.setText((CharSequence) app_preferences.getString("timerButton", "Start Timer"));
DatabaseHelper.customerFromDatabaseToList(this);
editor = app_preferences.edit();
editor.commit();
}
public void onDestroy() {
super.onDestroy();
editor.putLong("startTime", startTime);
editor.putString("zeitAnzeige", (String) displayTime.getText());
editor.putString("timerButton", (String) startEndButton.getText());
editor.putLong("endTime", endTime);
editor.putLong("totalTime", totalTime);
editor.putBoolean("running", app_preferences.getBoolean("running", false));
editor.commit();
this.finish();
}
public void onResume() {
super.onResume();
// saveCustomers();
// createDropDown();
}
public void startTimer(View view) {
editor = app_preferences.edit();
if(running == false) {
startTime = getTime();
running = true;
editor.putLong("startTime", startTime);
startEndButton.setText("End Timer");
displayTime.setText("Zeitstoppung läuft");
editor.putString("zeitAnzeige", (String) displayTime.getText());
editor.putString("timerButton", (String) startEndButton.getText());
editor.putBoolean("running", true);
editor.commit();
} else {
setSelectedCustomer();
endTime = getTime();
editor.putLong("endTime",endTime);
totalTime = endTime - startTime;
editor.putLong("totalTime", totalTime);
displayTime.setText(formatTime(totalTime));
editor.putString("zeitAnzeige", (String) displayTime.getText());
startEndButton.setText("Start Timer");
editor.putString("timerButton", (String) startEndButton.getText());
running = false;
editor.putBoolean("running", false);
editor.commit();
DatabaseHelper.timeToDatabase(String.valueOf(selectedCustomer.getId()),formatTime(totalTime),this);
// selectedCustomer.saveTimeToCustomer(selectedCustomer, formatTimeForCustomer(totalTime));
}
}
public String formatTime(Long totalTime) {
int hours = (int) ((totalTime / (1000*60*60)) % 24);
int minutes = (int) ((totalTime / (1000*60)) % 60);
int seconds = (int) (totalTime / 1000) % 60;
String time = (String.valueOf(hours) + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds));
return time;
}
public String formatTimeForCustomer(Long totalTime) {
StringBuilder time = new StringBuilder();
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
time.append((String.valueOf(year) + "." + String.valueOf(month) + "." + String.valueOf(day))).append(formatTime(totalTime));
return time.toString();
}
public void neuerKunde(View view) {
Intent intent = new Intent(this, AddKunde.class);
startActivity(intent);
}
public void kundenÜbersicht(View view) {
// setSelectedCustomer();
Intent intent = new Intent(this, DisplayCustomer.class);
startActivity(intent);
}
public long getTime() {
long millis = System.currentTimeMillis();
return millis;
}
public void setSelectedCustomer() {
if(kunden.size() > 0) {
if (spinner.getSelectedItem().toString() != null) {
String tempCustomer = spinner.getSelectedItem().toString();
for (Kunde k : kunden) {
if (k.getName().equals(tempCustomer)) {
selectedCustomer = k;
}
}
}
}
}
public void createDropDown() {
/*File file = new File(this.getFilesDir(),"kunden.ser"); NOT USED BECAUSE DATABASE WORKS
if(file.exists()) {
Kunde.importFromFile(this);
}*/
if (kunden.size() > 0) {
spinner = (Spinner) findViewById(R.id.chooseCustomer);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DisplayCustomer.namesOfCustomers());
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
}
}
DisplayCustomer(Where all customers are displayed with data from Database)
public class DisplayCustomer extends AppCompatActivity {
CustomerAdapter customerAdapter;
public ArrayAdapter<String> adapterCustomerView;
private ListView listCustomerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<Kunde> customerList = getCustomerObjects();
customerAdapter = new CustomerAdapter(this,customerList);
listCustomerView = (ListView)findViewById(R.id.list_View_Customers);
// adapterCustomerView = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namesOfCustomers());
listCustomerView.setAdapter(customerAdapter);
openCustomerDetails();
}
public static ArrayList<String> namesOfCustomers() {
ArrayList<String> customerNames = new ArrayList<>();
if(ZeitErfassen.kunden.size() > 0 ) {
for (Kunde k : ZeitErfassen.kunden) {
customerNames.add(k.getName());
}
}
return customerNames;
}
public static ArrayList<Kunde> getCustomerObjects() {
ArrayList<Kunde> customerList = new ArrayList<>();
if(ZeitErfassen.kunden.size() > 0 ) {
for (Kunde k : ZeitErfassen.kunden) {
customerList.add(k);
}
}
return customerList;
}
public void openCustomerDetails() {
listCustomerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Kunde kunde = new Kunde();
kunde = (Kunde)listCustomerView.getItemAtPosition(position);
Intent intent = new Intent(DisplayCustomer.this, DisplayDetailedCustomer.class);
intent.putExtra("selectedCustomerObject",(Parcelable)kunde);
startActivity(intent);
}
});
}
}
My CustomerAdapter to pass data from one intent to another.
public class CustomerAdapter extends ArrayAdapter<Kunde> {
public CustomerAdapter(Context context, ArrayList<Kunde> customerList) {
super(context,0,customerList);
}
public View getView(int position, View convertView, ViewGroup parent) {
//Data for this position
Kunde kunde = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.items_customer_layout, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvCustomerName);
// Populate the data into the template view using the data object
tvName.setText(kunde.getName());
// Return the completed view to render on screen
return convertView;
}
}
DatabaseHelper Class
public class DatabaseHelper {
public static RequestQueue requestQueue;
public static String host = "http://192.168.150.238/";
public static final String insertUrl = host+"insertCustomer.php";
public static final String showUrl = host+"showCustomer.php";
public static final String insertTimeUrl = host+"insertTime.php";
public static final String showTimeUrl = host+"showTimes.php";
public static void customerFromDatabaseToList(final Context context) {
//Display customer from database
requestQueue = Volley.newRequestQueue(context);
final ArrayList<String> customerNames = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray customers = response.getJSONArray("customers");
if(customers.length() > 0) {
for (int i = 0; i < customers.length(); i++) {
JSONObject customer = customers.getJSONObject(i);
String customerName = customer.getString("cus_name");
String customerAddress = customer.getString("cus_address");
int customerID = Integer.valueOf(customer.getString("cus_id"));
if (customerName != null && customerAddress != null) {
try {
Kunde k = new Kunde(customerName, customerAddress, customerID);
if (!listContainsObject(k)) {
ZeitErfassen.kunden.add(k);
}
} catch (Exception e) {
showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
}
} else {
showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
public static boolean listContainsObject(Kunde cust) {
for(Kunde k : ZeitErfassen.kunden) {
if(k.getId() == cust.getId()) {
return true;
}
}
return false;
}
public static void timeToDatabase(final String customer_id, final String time_value, final Context context) {
requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST, DatabaseHelper.insertTimeUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showAlert("Fehler","Fehler bei Verbindung zur Datenbank",context);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("customerid",customer_id);
parameters.put("timevalue",time_value);
return parameters;
}
};
requestQueue.add(request);
};
public static void showAlert(String title, String message, Context context) {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(message)
.setTitle(title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
}
public static ArrayList<String> timesFromDataBaseToList(final Context context,final int customer_id) {
requestQueue = Volley.newRequestQueue(context);
final String cus_id = String.valueOf(customer_id) ;
final ArrayList<String> customerTimes = new ArrayList<>();
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, showTimeUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response.toString());
JSONArray times = object.getJSONArray("customertimes");
if (times.length() > 0) {
for (int i = 0; i < times.length(); i++) {
JSONObject jsonObject = times.getJSONObject(i);
String timeValue = jsonObject.getString("time_value");
if (timeValue != null) {
customerTimes.add(timeValue);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Fehler beim Holen der Zeiten",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("cus_id",cus_id);
return parameters;
}
};
requestQueue.add(jsonObjectRequest);
return customerTimes;
};
}
DisplayDetailedCustomer / Display the times
public class DisplayDetailedCustomer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_detailed_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent getCustomerParcable = getIntent();
Kunde customer = getCustomerParcable.getExtras().getParcelable("selectedCustomerObject");
TextView displayCustomerNameDetailed =(TextView) findViewById(R.id.detailedCustomerViewName);
TextView displayCustomerAddressDetailed =(TextView) findViewById(R.id.detailedCustomerAddress);
ListView timeListView = (ListView)findViewById(R.id.detailedTimeListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, DatabaseHelper.timesFromDataBaseToList(this,customer.getId()));
timeListView.setAdapter(adapter);
displayCustomerNameDetailed.setText(customer.getName());
displayCustomerAddressDetailed.setText(customer.getAdresse());
}
}
Kunde Class / Customer Class with interface Parcelable
public class Kunde implements Serializable,Parcelable {
private String name;
private String adresse;
private int id;
public LinkedList<String> zeiten;
public Kunde(String name, String adresse) throws Exception{
setName(name);
setAdresse(adresse);
zeiten = new LinkedList<String>();
}
public Kunde(String name, String adresse,int id) throws Exception{
setName(name);
setAdresse(adresse);
setId(id);
zeiten = new LinkedList<String>();
}
public Kunde(){};
public void setId(int id) {
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name) throws Exception {
if(name != null) {
this.name = name;
} else throw new Exception("Name ist ungueltig! in setName");
}
public void setAdresse(String adresse) throws Exception{
if(adresse != null) {
this.adresse = adresse;
}else throw new Exception("Adresse ist ungueltig! in setAdresse");
}
public String getName() {
return name;
}
public String getAdresse() {
return adresse;
}
public void saveZeit(Long totalTime) {
zeiten.add(String.valueOf(totalTime));
}
public void saveTimeToCustomer(Kunde customer,String time){
customer.zeiten.add(time);
}
//------------------------------------Parcelable Methods to pass Daata from one Intent to another----------------------------------------
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
dest.writeString(this.adresse);
// dest.writeList(this.zeiten);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Kunde> CREATOR = new Parcelable.Creator<Kunde>() {
public Kunde createFromParcel(Parcel in) {
return new Kunde(in);
}
public Kunde[] newArray(int size) {
return new Kunde[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Kunde(Parcel in) {
LinkedList<String> zeiten = null;
id = in.readInt();
name = in.readString();
adresse = in.readString();
}
}
Thanks for taking your time!!

getting a error with my code private void update list everything from "this, mCommentList" is underlined in red

Could someone help me. I was following a very long tutorial and got to the end and can't fix this error. Starting at public void update list the code below is underlined in red and I can't seem to correct the problem.
public class readComments extends ListActivity {
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://120.120.1.100 /webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent(readComments.this, AddComment.class);
startActivity(i);
}
public void updateJSONdata() {
}
private void updateList() {
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(readComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//Problem starts here everything underlined in red
#Override
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME}, new int[]{R.id.title, R.id.message,
R.id.username});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}

Get JSON response when request post by volley

I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button nothing show up in Listview !!
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
SupportActivity.java
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aaa/getticket.php";
private RequestQueue requestQueue1;
int i ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("error")) {
Toast.makeText(supportActivity.this, "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject ticket ;
JSONArray jsonArray = new JSONArray("responseticket");
ticket = jsonArray.getJSONObject(Integer.parseInt(response));
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
SupportAdapter.java
public class supportAdapter extends ArrayAdapter<supportContent> {
private Context context;
private List<supportContent> contents;
public supportAdapter(Context context, List<supportContent> con){
super(context, R.layout.supportcontent, con);
this.contents = con;
}
#Override
public int getCount(){
return contents.size();
}
public View getView(int position, View convertview, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(getContext());
View supcon = inflater.inflate(R.layout.supportcontent, null);
TextView ticketnumber = (TextView)supcon.findViewById(R.id.ticketnumber);
ticketnumber.setText(contents.get(position).getTicketnumber());
TextView supportsubject = (TextView)supcon.findViewById(R.id.supportsubject);
supportsubject.setText(contents.get(position).getSubject());
TextView response = (TextView)supcon.findViewById(R.id.response);
response.setText(contents.get(position).getResponse());
return supcon;
}
}
Parse your response as below -
JSONObject jObj = new JSONObject(response);
JSONArray jResponseTicketarray = jObj.getJSONArray("responseticket");
JSONObject jTicket = jResponseTicketarray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
response - returned Json response in onResponse() mth.
jResponseTicketarray.getJSONObject(0); - here '0' is first element in ResponseTicketArray. If der are multiple object u might wanna iterate thr loop and extract required fields.
Modify below code too -
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
to below -
supportContent support = new supportContent();
support.setTicketnumber(TicketNumber);
support.setSubject(Subject);
support.setResponse(Response);

Categories

Resources