How to get data of current id on recyclerview - java

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. :)

Related

Error: No adapter attached; skipping layout

I know this question has been asked so many times, but none of the solutions answered there seems to solve my problem.
Most of the solutions suggested attaching an adapter (setadapter()) and I have done that. But the problem still seems to persist.
I also checked if my listitems are empty and it isn't.
I have attached the adapter in a function loadUserAccounts().
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_accounts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Swipe to refresh
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.userSwipeRefresh);
//Recycler View
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//Function to load the users to the recycler view
loadUserAccounts();
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
swipeRefresh.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("Swipe_log: ", "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
loadUserAccounts();
}
}
);
}
and this is my loadUserAccounts() function:
/**
* Function to load the user account
* into the recycler view from the log database
*/
public void loadUserAccounts(){
String tag_string_req = "req_user_acc";
clear();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_USER_ACCOUNTS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
listItems.add(item);
}
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error!=null && error.getMessage() !=null){
Log.e(TAG,"User Accounts Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_LONG).show();
}
}
});
//Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
if (swipeRefresh == null)
return;
else {
if (swipeRefresh.isRefreshing()) {
swipeRefresh.setRefreshing(false);
}
}
}
My adapter class RecyclerViewUserAdapter
public class RecyclerViewUserAdapter extends RecyclerView.Adapter<RecyclerViewUserAdapter.ViewHolder> {
private List<ListItem_RecyclerView_User> listItems;
private Context context;
public RecyclerViewUserAdapter(List<ListItem_RecyclerView_User> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_recycler_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewUserAdapter.ViewHolder holder, int position) {
ListItem_RecyclerView_User listItem = listItems.get(position);
holder.txtUserName.setText(listItem.getTxtUserName());
holder.txtUserCpf.setText(listItem.getTxtUserCpf());
holder.txtAccountType.setText(listItem.getTxtAccountType());
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
date = df.parse(listItem.getTxtCreatedDate());
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String loginTime = sdf.format(date);
holder.txtCreatedDate.setText(loginTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView txtUserName;
private TextView txtUserCpf;
private TextView txtAccountType;
private TextView txtCreatedDate;
public ViewHolder(View itemView) {
super(itemView);
txtUserName = (TextView) itemView.findViewById(R.id.txtUserName);
txtUserCpf = (TextView) itemView.findViewById(R.id.txtUserCpf);
txtAccountType = (TextView) itemView.findViewById(R.id.txtAccountType);
txtCreatedDate = (TextView) itemView.findViewById(R.id.txtCreatedDate);
}
}
}
Try this...
modify that getItemCount() to like this.
#Override
public int getItemCount() {
return listItems.size();
}
Try this
Create your adapter with empty list data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
// your normal code
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
// create new adapter
recyclerViewUserAdapter = new RecyclerViewUserAdapter(new ArrayList<>(), userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//your normal code
}
In your response
#Override
public void onResponse(String response) {
try {
List<ListItem_RecyclerView_User> responseList = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
responseList.add(item);
}
/*recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);*/
// write method to update your data
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
In your adapter create method
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged():
}

error with loading data from web in android

i've added a column (named load_more) to the end of a recyclerview and each time i touch this column it should download ten more columns from a url. the first time that I touch load_more, it works properly but for the second time, program crashes.
this is the code of loading data to the recyclerview:
public class category extends AppCompatActivity {
private String url = "http://iranradiotherapy.ir/api/get_category_posts/?include=title,date&id=";
private RequestQueue requestQueue;
private ArrayList<HashMap<String, String>> data;
private RecyclerView recyclerView;
private adapter adapter;
private int page_counter;
private String page_number;
private boolean flag;
private int current;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
Bundle b = getIntent().getExtras();
final String cat_id = b.getString("category_id");
url += cat_id;
Toast.makeText(category.this, url, Toast.LENGTH_SHORT).show();
data = new ArrayList<>();
flag = true;
page_counter = 1;
page_number= "&page=";
requestQueue = Volley.newRequestQueue(this);
get_data();
}
private void get_data() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url + page_number + page_counter, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray posts = response.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
HashMap<String, String> hashMap = new HashMap<>();
JSONObject temp = posts.getJSONObject(i);
String post_title = temp.getString("title");
String post_id = temp.getString("id");
String post_date = temp.getString("date");
hashMap.put("post_title", post_title);
hashMap.put("post_date", post_date);
hashMap.put("post_id", post_id);
data.add(hashMap);
}
final HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("load_more", "load_more");
data.add(hashMap);
recyclerView = (RecyclerView) findViewById(R.id.category_recycler_view);
adapter = new adapter(data);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
flag = true;
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), new RecyclerTouchListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if (data.get(position).equals(hashMap)) {
load_more();
}
else {
Intent i = new Intent(category.this, post.class);
i.putExtra("post_id", data.get(position).get("post_id"));
category.this.startActivity(i);
}
}
}));
} catch (Exception e ) {
Toast.makeText(category.this, "error 1 : " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(category.this, "error 2 : " + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
private void load_more() {
if (flag){
flag = false;
Toast.makeText(this, "load more data " + current, Toast.LENGTH_SHORT).show();
page_counter++;
get_data();
data.remove(data.size() - 1 );
}
}
}
and this is the adapter :
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if (position + 1 == data.size()) {
holder.title.setVisibility(View.INVISIBLE);
holder.date.setVisibility(View.INVISIBLE);
holder.load_more.setVisibility(View.VISIBLE);
} else {
HashMap<String, String> d = data.get(position);
holder.title.setText(d.get("post_title"));
holder.date.setText(d.get("post_date"));
holder.load_more.setVisibility(View.INVISIBLE);
}
}

How to solve the error like java.lang.Throwable: setStateLocked?

I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);

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!!

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