sorting a ListView by number - android

sort ListView Android by float number ...
I have a listview price type float display of a mysql database ,,
I want to sort it (by order) but I have not found a solution ..
how can I do it please !!!
it's the code of my listView with prices done !!
private class GetHttpResponse extends AsyncTask<Void, Void, Void>{
public Context context;
String ResultHolder;
List<subjects> subjectsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new
HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
subjectsList = new ArrayList<subjects>();
for(int i=0; i<jsonArray.length(); i++)
{ subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
subjects.SubjectName = jsonObject.getString("tarif");
subjectsList.add(subjects);
} }
catch (JSONException e) {
e.printStackTrace();
} } } else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(),
Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{ progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
if(subjectsList != null)
{
ListAdapterClass adapter = new ListAdapterClass(subjectsList,
context);
SubjectListView.setAdapter(adapter);
SubjectListView.setOnItemClickListener(new
AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int pos, long id) {
String selectedItem =
parent.getItemAtPosition(pos).toString();
Toast.makeText(TechnicienActivity.this,selectedItem,
Toast.LENGTH_SHORT).show();
Intent intent = new
Intent(getApplicationContext(),Main2Activity.class);
intent.putExtra("Position" , String.valueOf(id));
startActivity(intent);
} }); } } }

You can sort the list by using
Collections.sort(list);
and then set this to the listview.
Example;
subjectsList.add(subjects);
Collections.sort(subjectsList);

Related

search in listview only refreshes the whole list and does not get the result into list

I am getting the data from server using JSON and when i try to search in the listview it just refreshes the whole list and does not narrate it, but when i debug i can see the result on getfilter is right right and it drugsFiltered = (ArrayList<drugs_json_data>) results.values; does have the filtered data inside it. just the listview.setadaptor is being done inside onPostExecute of the asynctask.
here is my adapter code:
public class drugs_adaptor_listView extends ArrayAdapter<drugs_json_data> implements Filterable {
ArrayList<drugs_json_data> drugs;
ArrayList<drugs_json_data> drugsFiltered;
Context context;
int resource;
public drugs_adaptor_listView(Context context, int resource, ArrayList<drugs_json_data> drugs) {
super(context, resource, drugs);
this.drugs = drugs;
this.drugsFiltered = drugs;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View r = convertView;
ViewHolder viewHolder;
if (r == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
r = layoutInflater.inflate(R.layout.row_layout_drugs, null, true);
viewHolder = new ViewHolder(r);
r.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) r.getTag();
}
drugs_json_data drugs_json_data = getItem(position);
viewHolder.txtDrugId.setText(drugs_json_data.getDrugId());
viewHolder.txtDrugName.setText(drugs_json_data.getDrugName());
viewHolder.txtDrugCategory.setText(drugs_json_data.getDrugCategory());
Picasso builder = new Picasso.Builder(context).build();
builder.load(drugs_json_data.getDrugImage()).memoryPolicy(MemoryPolicy.NO_STORE).placeholder(R.drawable.ic_launcher_foreground).into(viewHolder.imageView);
return r;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
drugsFiltered = (ArrayList<drugs_json_data>) results.values; // has the filtered values
if (results.count>0) {
notifyDataSetChanged(); // notifies the data with new filtered values
}else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<drugs_json_data> FilteredArrList = new ArrayList<>();
if (drugs == null) {
drugs = new ArrayList<>(drugsFiltered); // saves the original data in mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = drugs.size();
results.values = drugs;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < drugs.size(); i++) {
String data = drugs.get(i).getDrugName();
if (data.startsWith(constraint.toString())) {
FilteredArrList.add(new drugs_json_data(drugs.get(i).getDrugId(), drugs.get(i).getDrugName(), drugs.get(i).getDrugCategory(), drugs.get(i).getDrugImage()));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
class ViewHolder {
TextView txtDrugId, txtDrugName, txtDrugCategory;
ImageView imageView;
ViewHolder(View v) {
txtDrugId = v.findViewById(R.id.txtDrugId);
txtDrugName = v.findViewById(R.id.txtDrugName);
txtDrugCategory = v.findViewById(R.id.txtDrugCat);
imageView = v.findViewById(R.id.ImageViewDrug);
}
}
}
here is the data model:
public class drugs_json_data {
private String drugImage;
private String drugName;
private String drugCategory;
private String drugId;
public drugs_json_data(String drugImage, String drugName, String drugCategory, String drugId) {
this.drugImage = drugImage;
this.drugName = drugName;
this.drugCategory = drugCategory;
this.drugId = drugId;
}
public String getDrugImage() {
return this.drugImage;
}
public void setDrugImage(String drugImage) {
this.drugImage = drugImage;
}
public String getDrugName() {
return this.drugName;
}
public void setDrugName(String drugName) {
this.drugName = drugName;
}
public String getDrugCategory() {
return this.drugCategory;
}
public void setDrugCategory(String drugCategory) {
this.drugCategory = drugCategory;
}
public String getDrugId() {
return this.drugId;
}
public void setDrugId(String drugId) {
this.drugId = drugId;
}
}
and here is the main activity code:
public class clerk_drugs extends AppCompatActivity {
ListView listView;
Button createDrug;
String drug_id, json_drug;
TextView noMed;
EditText searchTxt;
JSONObject jsonObject;
JSONArray jsonArray;
ArrayList<drugs_json_data> arrayList;
drugs_adaptor_listView adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clerk_drugs);
createDrug = findViewById(R.id.create_drug);
arrayList = new ArrayList<>();
listView = findViewById(R.id.list_drugs);
noMed = findViewById(R.id.no_med);
searchTxt = findViewById(R.id.listSearch);
searchTxt.setSingleLine(true);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
new ReadJSON().execute("http://(mylink)").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
jsonObject = new JSONObject(json_drug);
jsonArray = jsonObject.getJSONArray("server_response");
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drug_id = ((TextView) view.findViewById(R.id.txtDrugId)).getText().toString();
for (int i = 0; i<jsonArray.length(); i++){
try {
JSONObject jobj = jsonArray.getJSONObject(i);
String drugid = jobj.getString("drug_id");
if(drugid.equals(drug_id)) {
String drugname = jobj.getString("drug_name");
String drugcategory = jobj.getString("drug_category");
String drugdescription = jobj.getString("drug_description");
String drugphoto = jobj.getString("drug_photo");
drug_update_dialog drug_update_dialog = new drug_update_dialog();
Bundle args = new Bundle();
args.putString("drug-id", drug_id);
args.putString("drug-name", drugname);
args.putString("drug-category", drugcategory);
args.putString("drug-description", drugdescription);
args.putString("drug_photo",drugphoto);
drug_update_dialog.setArguments(args);
drug_update_dialog.show(getSupportFragmentManager(),"ویرایش اطلاعات دارو");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
searchTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
searchTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
hideKeyboard(v);
}
}
});
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class ReadJSON extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
for(int i=0; i<jsonArray.length();i++){
JSONObject drugObj = jsonArray.getJSONObject(i);
arrayList.add(new drugs_json_data(
drugObj.getString("drug_photo"),
drugObj.getString("drug_name"),
drugObj.getString("drug_category"),
drugObj.getString("drug_id")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new drugs_adaptor_listView(
getApplicationContext(), R.layout.row_layout_drugs, arrayList
);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
if (adapter.getCount()==0){
noMed.setVisibility(View.VISIBLE);
}
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try{
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line=bufferedReader.readLine())!=null){
content.append(line).append("\n");
}
bufferedReader.close();
}catch (Exception e){
e.printStackTrace();
}
json_drug = content.toString();
return content.toString();
}
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(this,patient_mainPage.class);
startActivity(intent);
}
public void createDrugDialog(View view){
openDrugDialog();
}
private void openDrugDialog() {
drug_add_dialog drug_add_dialog = new drug_add_dialog();
drug_add_dialog.show(getSupportFragmentManager(),"ثبت داروی جدید");
}
}
I would be grateful if someone could help.
UPDATED
In getView method in Adapter
Replace
drugs_json_data drugs_json_data = getItem(position);
With
drugs_json_data drugs_json_data = drugsFiltered.get(position);

After pressing back button, previous activity (listview) is emtpty

In my android project i have a listview with items loaded from an online database. When i click on an item i go to another class where i can delete or update it. My problem is that when i press the back button, my listview is empty. I tried onBackPressed with intent to go to previous activity but it is empty again. I want to reload my listview when from a clicked item i press the back button. Below is my code.
The listview:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
//finish();
}
});
search = (EditText)findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
// check student's name whether contain text entered in search box
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}}
And the code from item click:
public class SingleStudent extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://sissy-nickels.000webhostapp.com/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://sissy-nickels.000webhostapp.com/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,SURNAME,DEPT,REGNUM,GRADE;
String NameHolder, SurnameHolder, DeptHolder, RegnumHolder, GradeHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlestudent);
NAME = (TextView)findViewById(R.id.name);
SURNAME = (TextView)findViewById(R.id.surname);
DEPT = (TextView)findViewById(R.id.dept);
REGNUM = (TextView)findViewById(R.id.regnum);
GRADE = (TextView)findViewById(R.id.grade);
UpdateButton = (Button)findViewById(R.id.BDel);
DeleteButton = (Button)findViewById(R.id.BUp);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SingleStudent.this,StudentUpdate.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("name", NameHolder);
intent.putExtra("surname", SurnameHolder);
intent.putExtra("dept", DeptHolder);
intent.putExtra("regnum", RegnumHolder);
intent.putExtra("grade", GradeHolder);
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(SingleStudent.this, "Φόρτωση", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(SingleStudent.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(SingleStudent.this,"Φόρτωση",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(SingleStudent.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("Name").toString() ;
SurnameHolder = jsonObject.getString("Surname").toString() ;
DeptHolder = jsonObject.getString("Dept").toString() ;
RegnumHolder = jsonObject.getString("Regnum").toString() ;
GradeHolder = jsonObject.getString("Grade").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
SURNAME.setText(SurnameHolder);
DEPT.setText(DeptHolder);
REGNUM.setText(RegnumHolder);
GRADE.setText(GradeHolder);
}
}}
Than you in advance!
try this on AllStudents activity
#Override
protected void onResume() {
super.onResume();
if (studentList != null && studentList.size()>0) {
ListAdapter adapter = new ListAdapter(studentList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
*Note
when you make a search you run the filterStudents() method
and replace the current list in the adapter
ListAdapter adapter = new ListAdapter(filteredList, this);
but make sure that if you search for nothing .. return the original list
ListAdapter adapter = new ListAdapter(studentList, this);
or you will get an empty list view
You should not recreate from secondActivity. You just finish it when your work is done in secondActivity. Which means, simply you have to do the below in your secondActivity.
#Override
public void onBackPressed() {
super.onBackPressed();
}

I used PagerAdapter for sliding images its not notifying properly

I used PagerAdapter for sliding images and i added a favorite button too in that sliding image. After clicking favorite button its not getting notified properly image not turns to unfavorite icon.
it is for loading api
private class PremiumProjectLoad extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url= ApiLinks.PremiumProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(getActivity(),null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("cityID",CommonStrings.cityID);
if(session.isLoggedIn()){
params.put("userID",UserLogin.get(SessionManager.KEY_CUSTOMER_ID));
}
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String Status=json.optString("status");
String Message=json.optString("message");
CommonImagePath=json.optString("imagepath");
PremiumDataArray.clear();
if(Status.equals("ok")){
JSONArray DataArray=json.optJSONArray("data");
if(DataArray!=null && DataArray.length()>0) {
for (int i = 0; i < DataArray.length(); i++) {
JSONObject DataObj = DataArray.optJSONObject(i);
String projectID = DataObj.optString("projectID");
String projectName = DataObj.optString("projectName");
String propertyUnitPriceRange = DataObj.optString("propertyUnitPriceRange");
String projectOfMonthImage = DataObj.optString("projectOfMonthImage");
String propertyUnitBedRooms = DataObj.optString("propertyUnitBedRooms");
String projectBuilderName = DataObj.optString("projectBuilderName");
String propertyTypeName = DataObj.optString("propertyTypeName");
String purpose = DataObj.optString("purpose");
String projectBuilderAddress = DataObj.optString("projectBuilderAddress");
String projectFavourite = DataObj.optString("projectFavourite");
PremiumData premiumData = new PremiumData();
premiumData.setProjectID(projectID);
premiumData.setProjectName(projectName);
premiumData.setPropertyUnitPriceRange(propertyUnitPriceRange);
premiumData.setProjectOfMonthImage(projectOfMonthImage);
premiumData.setPropertyUnitBedRooms(propertyUnitBedRooms);
premiumData.setProjectBuilderName(projectBuilderName);
premiumData.setPropertyTypeName(propertyTypeName);
premiumData.setPurpose(purpose);
premiumData.setProjectBuilderAddress(projectBuilderAddress);
premiumData.setProjectFavourite(projectFavourite);
PremiumDataArray.add(premiumData);
}
LoopViewPager viewpager = (LoopViewPager) homeView.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) homeView.findViewById(R.id.indicator);
// if(pagerAdapter==null)
pagerAdapter = new PremiumProjectAdapter(getActivity(), PremiumDataArray);
viewpager.setAdapter(pagerAdapter);
indicator.setViewPager(viewpager);
// pagerAdapter.notifyDataSetChanged();
}
}
else {
Toast.makeText(getActivity(),Message, Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
pager adapter
public class PremiumProjectAdapter extends PagerAdapter {
private final Random random = new Random();
private ArrayList<PremiumData> mSize;
Context mContext;
LayoutInflater mLayoutInflater;
String ProjectID;
String path=CommonImagePath+"/uploads/projectOfMonth/orginal/";
// public PremiumProjectAdapter() {
// }
public PremiumProjectAdapter(Context contexts, ArrayList<PremiumData> count) {
mSize = count;
mContext=contexts;
}
#Override public int getCount() {
return mSize.size();
}
#Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
}
#Override public Object instantiateItem(ViewGroup view, final int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.home_premium_layout, view, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.premium_ProImage);
TextView ProjectName = (TextView) itemView.findViewById(R.id.premium_ProName);
TextView ProjectUnitPrice = (TextView) itemView.findViewById(R.id.premium_UnitPrice);
TextView ProjectUnitBedroom = (TextView) itemView.findViewById(R.id.premium_UnitBedrooms);
TextView ProjectAddress = (TextView) itemView.findViewById(R.id.premium_ProAddress);
ImageView unshortlisted = (ImageView) itemView.findViewById(R.id.unshortlisted);
ImageView shortlisted = (ImageView) itemView.findViewById(R.id.shortlisted);
final PremiumData data = mSize.get(position);
if (data.getProjectFavourite() != null) {
if (data.getProjectFavourite().equals("ShortListed")) {
shortlisted.setVisibility(View.VISIBLE);
unshortlisted.setVisibility(View.GONE);
} else {
shortlisted.setVisibility(View.GONE);
unshortlisted.setVisibility(View.VISIBLE);
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange(), Html.FROM_HTML_MODE_COMPACT));
}else{
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange()));
}
ImageLoader.getInstance().displayImage(path+data.getProjectOfMonthImage(), imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(!data.getProjectName().equals("null") && data.getProjectName().length()>30){
String s = data.getProjectName().substring(0, 25);
String subString = s + "...";
ProjectName.setText(subString);
}
else{
ProjectName.setText(data.getProjectName());
}
ProjectUnitBedroom.setText(data.getPropertyUnitBedRooms());
ProjectAddress.setText(data.getProjectBuilderAddress());
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent DetailsAction=new Intent(mContext, DetailsActivity.class);
DetailsAction.putExtra("projectID",data.getProjectID());
DetailsAction.putExtra("purpose",data.getPurpose());
mContext.startActivity(DetailsAction);
}
});
unshortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!session.isLoggedIn()){
Intent toLogin=new Intent(mContext, LoginActivity.class);
CommonStrings.FromSearchIndex="true";
mContext.startActivity(toLogin);
}else{
ProjectID=data.getProjectID();
new ShortlistProject().execute();
}
}
});
shortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProjectID=data.getProjectID();
new UnShortlistProject().execute();
}
});
view.addView(itemView);
return itemView;
}
private class ShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.AddShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
//SearchFragment.getInstance().onResume();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
private class UnShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.RemoveShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
// HomeFragment.getInstance().async_Premium();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
As far as i am able to understand your question you want favorite and unfavorite functionality by adapter . Please use this code below to achieve that :
public class CustomGridAdapterFoodDrink extends BaseAdapter {
private Context mContext;
private ProgressDialog loading;
ArrayList<FoodDrink> foodDrinkArrayList = new ArrayList<>();
SharedPreferences pref;
String userId;
String like_dislike_value = "Like";
String likeValueStr = "1";
boolean like = true;
int positionVal = 444;
HashMap<Integer,Boolean> state = new HashMap<>();
public CustomGridAdapterFoodDrink(Context c, ArrayList<FoodDrink> foodDrinkArrayList) {
mContext = c;
this.foodDrinkArrayList = foodDrinkArrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodDrinkArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView projectNamtTxtView = (TextView) grid.findViewById(R.id.projectName);
TextView totalOfferText = (TextView) grid.findViewById(R.id.TotalOffers);
ImageView merchantImage = (ImageView) grid.findViewById(R.id.merchantImage);
final ImageView like_dislike_icon = (ImageView) grid.findViewById(R.id.like_dislike_icon);
totalOfferText.setText(foodDrinkArrayList.get(position).getOffers());
projectNamtTxtView.setText(foodDrinkArrayList.get(position).getProject_name());
Glide.with(mContext)
.load(foodDrinkArrayList.get(position).getProject_photo())
.centerCrop()
.placeholder(R.drawable.review_pro_pic1)
.crossFade()
.into(merchantImage);
like_dislike_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", null);
/* if(state.size()> 0){
like = state.get(position);*/
if (!like) {
like = true;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
} else {
like = false;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it);
likeDislike2(foodDrinkArrayList.get(position).getID(), "0");
}
/* } else {
like = true;
state.put(position,like);
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
}*/
// if(positionVal !=position) {
// likeValueStr ="1";
// positionVal = position;
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
// else {
// likeValueStr ="0";
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
}
});
} else {
grid = (View) convertView;
}
return grid;
}
private void likeDislike(String merchantId, final String like_dislike, final ImageView imageView) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
if (msg.equalsIgnoreCase("Like")) {
imageView.setImageResource(R.mipmap.like_it_act);
} else {
imageView.setImageResource(R.mipmap.like_it);
}
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
private String getlikeUrl(String userId, String merchantId, String like_dislike) {
String url = "";
try {
url = NetworkURL.URL
+ "likeMerchant"
+ "?user_id=" + URLEncoder.encode(new Global().checkNull(userId), "UTF-8")
+ "&merchant_id=" + URLEncoder.encode(new Global().checkNull(merchantId), "UTF-8")
+ "&like_dislike=" + URLEncoder.encode(new Global().checkNull(like_dislike), "UTF-8")
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
return url;
}
private void likeDislike2(String merchantId, final String like_dislike) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
}

My questions is, how do I pass the list data i have obtained from JSON in a fragment to an activity?

This is my Fragment Class - Here i get the JSON array object and call the adapter class for setting it. In the corressponding XML file, i have used a card view and lsit view to display the data. i want to know how to implement a onItemClickListener{} function so that i can go to another activity and display the list in a more detailed manner.
{
String url = "http://www.appplay.in/student_project/public/staff_details";
ProgressDialog mProgressDialog;
ListView lvDetail;
Context context;
ArrayList<staff_model> myList = new ArrayList<>();
ListView lv;
public static ArrayList<staff_model> staff_array;
JSONObject jsonObject;
JSONObject jsonKey;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
context=container.getContext();
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
lvDetail = (ListView) v.findViewById(R.id.CustomList);
// submit=(Button)v.findViewById(R.id.button) ;
new GetGalleryimage().execute();
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent in = new Intent(getActivity(), Staff_Main.class);
startActivity(in);
}
});
return v;
}
public void positionAction(View view) {
int position = (int) view.getTag();
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
private class GetGalleryimage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("User_Details");
for(int i=0; i<jsonarr.length(); i++)
{
JSONObject jsonObject = jsonarr.getJSONObject(i);
myList.add(new staff_model(jsonObject.getString("name"),jsonObject.getString("dob"),jsonObject.getString("occupation"),jsonObject.getString("emailid"),jsonObject.getString("contact"),jsonObject.getString("timetable"),jsonObject.getString("image")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v("result",""+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
staff_BaseAdapter rcAdapter = new staff_BaseAdapter(getActivity(),0, myList);
lvDetail.setAdapter(rcAdapter);
}
}
public class MAP_Detailservice extends
AsyncTask<String, String, String> {
Context mContext;
JSONObject mJsnObj;
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
showProgress();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
JSONObject json = new JSONObject();
String cricketAllMatchesLink = "http://www.appplay.in/student_project/public/staff_details";
try {
return String.valueOf(HttpUtils.getJson(cricketAllMatchesLink));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.v("POST EXECUTE", "RESULT :" + result);
super.onPostExecute(result);
hideProgress();
// mProgressDialog.dismiss();
// if (HttpUtils.status == 408) {
// Toast.makeText(getActivity(), "Conection Lost ",
// Toast.LENGTH_SHORT).show();
// }
try {
JSONArray array = new JSONArray(result);
JSONObject mJsonObject = array.getJSONObject(0);
// ArrayList<user_agent> GetSearchResults();
ArrayList<staff_model> staff_result = new ArrayList<staff_model>();
/**
* Question Array Parsing
*/
JSONArray jsonQuesstionsArray = mJsonObject
.getJSONArray("User_Details");
for (int i = 0; i < jsonQuesstionsArray.length(); i++) {
// Reading questions
JSONObject jsonQuestionObject = jsonQuesstionsArray
.getJSONObject(i);
String name = jsonQuestionObject.getString("name");
String dob = jsonQuestionObject.getString("dob");
String occupation = jsonQuestionObject.getString("occupation");
String emailid = jsonQuestionObject.getString("emailid");
String contact = jsonQuestionObject.getString("contact");
String timetable = jsonQuestionObject.getString("timetable");
String image = jsonQuestionObject.getString("image");
}
lvDetail.setAdapter(new staff_BaseAdapter(
getActivity(), 0,staff_result));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void showProgress() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Loading please wait");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
public void hideProgress() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onDestroy(){
super.onDestroy();
if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
mProgressDialog.cancel();
}
}
}
This is my Adapter class - Where I have gotten the data and set the code
ArrayList<StaffList> myList = new ArrayList<StaffList>();
LayoutInflater inflater;
Context context;
public StaffBaseAdapter(Context context, ArrayList<StaffList> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public StaffList getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.staff_list_view, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
StaffList currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
}
}
}
This is my Model Class
String title;
int imgResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
first your model class "staff_model" implement parcelable it will help to transfer your single model item pass to other activity.
Then add ItemClickListener in your listview
add this into your getView function
MyViewHolder rowHolder=new MyViewHolder(convertView);
rowHolder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do whatever u want
}
});
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here you can convert your json to string
startActivity(new Intent(this, MainActivity.class).putExtra("myList",new Gson().toJson(list)));
}
});
and in your receiving activity
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list1=new Gson().fromJson(getIntent().getStringExtra("myList"),type);
Here Specify the TypeToken .You will have the exact json that you passed in the intent.

list of brands not displaying in a spinner

Hi in the below code I am displaying two spinner one is for displaying brand name and another for displaying model name.
I am getting the response from server like this:
{"RESULT":"SUCCESS","BRANDS":[{"BRANDID":"14","BRANDNAME":"471"},{"BRANDID":"3","BRANDNAME":"ACE"},{"BRANDID":"4","BRANDNAME":"ADLER"},{"BRANDID":"5","BRANDNAME":"ALIEN"},{"BRANDID":"6","BRANDNAME":"ARTISAN-TORO"},{"BRANDID":"7","BRANDNAME":"ASSOCIATED PACIFIC"},{"BRANDID":"8","BRANDNAME":"ASTEX"},{"BRANDID":"9","BRANDNAME":"BERNINA"},{"BRANDID":"10","BRANDNAME":"BONIS"},{"BRANDID":"11","BRANDNAME":"BROTHER"},{"BRANDID":"12","BRANDNAME":"BROTHER "},{"BRANDID":"13","BRANDNAME":"CHANDLER"},{"BRANDID":"15","BRANDNAME":"CINCINNATI"},{"BRANDID":"16","BRANDNAME":"CONSEW"},{"BRANDID":"17","BRANDNAME":"CONSEW\/SEIKO"},{"BRANDID":"18","BRANDNAME":"DENNISON"},{"BRANDID":"19","BRANDNAME":"DURKOPP ADLER"},{"BRANDID":"20","BRANDNAME":"EAGLE"},{"BRANDID":"21","BRANDNAME":"EASTMAN"},{"BRANDID":"22","BRANDNAME":"EASTMAN CARDINAL"},{"BRANDID":"23","BRANDNAME":"ECONOSEW"},{"BRANDID":"1","BRANDNAME":"usha"}]}
Model Response:
{"RESULT":"SUCCESS","MODELS":[{"MODELNAME":"150","MODELID":"2"},{"MODELNAME":"C150WS","MODELID":"3"},{"MODELNAME":"HC720A","MODELID":"4"}
Based on the brand i want to display model names.
java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url","" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.d("Brand_result","" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
spinner_fn();
Log.i("listbrands", " " + listBrands);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}
//ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext()
// ,android.R.layout.simple_spinner_item,listBrands_String);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}

Categories

Resources