I am currently making an app where the user can access study material from a list view of different subjects.
In my database table where the subject names are fetched from also has a column which has a file path to a folder on my online server. Each subject has an individual folder on the server.
How would I go about adding to my code so that when a user clicks on a subject on the list, the content of their specific folder displays on a new activity?
here is my code at the moment of a simple list view:
public class FindMaterialActivity extends Activity {
private ListView list;
private ArrayList<String> subjects;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_material2);
list = (ListView) findViewById(R.id.list);
subjects = new ArrayList<String>();
getData();
}
private void getData() {
//Creating a string request
StringRequest stringRequest = new StringRequest(SubConfig.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(SubConfig.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getSubjects(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getSubjects(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
subjects.add(json.getString(SubConfig.TAG_SUBJECTS));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
list.setAdapter(new ArrayAdapter<String>(FindMaterialActivity.this, android.R.layout.simple_list_item_1, subjects));
}
}
and subject config.java
public class SubConfig {
//JSON URL
public static final String DATA_URL = "http://opuna.co.uk/subject_api/FetchSub.php";
//Tags used in the JSON String
public static final String TAG_SUBJECTS = "Subject_Name";
public static final String TAG_SUB_ID = "Sub_id";
//JSON array name
public static final String JSON_ARRAY = "result";
}
Store the meta about the sub folders in your database as you did for subjects and get the meta using JSON in your app as you got for subjects and show them in a custom layout made of your own.
Related
I'm currently stuck on how I'm going to display my data to my spinner. So basically I am using Websocket to receive data and run it on my UI thread my problem is that there is no list of data showing in my spinner.
Here is my code:
WayPointData = new SubscribedData<>();
final Type WayPointType = new TypeToken<SubscribedData<WayPoint>>() {
}.getType();
/** an ID for the spinner **/
spin = (Spinner) findViewById(R.id.spinner);
final SpinnerAdapter adapter = new ArrayAdapter<String>(Pop.this, android.R.layout.simple_spinner_item);
spin.setAdapter(adapter);
rosbridge = new RosbridgeListener("ws://10.24.204.231:9090");
rosbridge.setOnDataReceivedListener(new RosbridgeMessageListener() {
/**
* a running thread that when the connection is made the data of the topic will serialize and deserialized java objects
* to (and from) JSON.
* #param msg
*/
#Override
public void onDataReceived(final String msg) {
try {
runOnUiThread( new Runnable() {
#Override
public void run() {
try {
WayPointData = new Gson().fromJson(msg,WayPointType);
JSONObject jsonObject = new JSONObject();
JSONArray wayPointJsonArray = jsonObject.getJSONObject("msg").getJSONArray("waypoints");
for (int i = 0; i < wayPointJsonArray.length(); i++) {
JSONObject wayPointJsonObject = wayPointJsonArray.getJSONObject(i);
// Parse name
String name = wayPointJsonObject.getString("name");
WayPoint wayPoint = new WayPoint();
wayPoint.name = name;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
/** a msg that will display once the data is received **/
Log.d("B9T", String.format("Received data: %s", msg));
} catch (Exception e) {
e.printStackTrace();
}
}
});
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int p, long id) {
WayPoint wayPoint = (WayPoint) parent.getItemAtPosition(p);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Thanks to anyone who can help me!
add array when you initing your adapter:
final SpinnerAdapter adapter = new ArrayAdapter<String>(Pop.this, android.R.layout.simple_spinner_item, yourStringArray);
if you make changes later (will receive list from server) just setup array that you used before with new data and use adapter.notifyDataSetChanged()
Here I can see you don't pass json string to JSONObject that's why your main JSON object is an empty json object.
You should pass the JSON string to the JSONObject parameter like below.
JSONObject jsonObject = new JSONObject(msg); // here you have to add your json string in JSONObject parameter
Hope it helps you.
I am just getting into Android Architecture and have encountered an issue after following this tutorial by mitch:
ViewModel doesn't show any data from the internet- I'm using volley- on first run.
The UI remains blank and only shows data on the views only onChange. i.e A screen rotation/refresh
If I manually set this data, it shows them on first run as required
i.e dataSet.add(new DecodeHouseDetails(1,1,1,"H2345","treutue.jpg","House 1","4345423232312","3224342434232") ); //Add data to the mutatable list
But once I include the network data, it misbehaves.
I have tried checking if my repository could be returning a null list on first run but the toast attached inside the repository shows that the data was well received, only that I dont understand why it wont display until either a change in screen rotation or a refresh
My Repository
public class GetHouseDetailsRepository {
private Context mContext;
private static final String URL_initializeDashboard= CustomFunctions.root_house_admin_url+"initialize_dashboard";
CustomFunctions func= new CustomFunctions();
private static GetHouseDetailsRepository instance;
private ArrayList<DecodeHouseDetails> dataSet= new ArrayList<>();
private JSONObject jsonObject;
public static GetHouseDetailsRepository getInstance(){
if(instance == null){
instance = new GetHouseDetailsRepository();
}
return instance;
}
//Make a mutable list of the data that we will be getting from the database
public MutableLiveData<List<DecodeHouseDetails>> getHouseDetails(Context mContext){
this.mContext=mContext;
getDatabaseHouseDetails();
MutableLiveData<List<DecodeHouseDetails>> myData= new MutableLiveData<>();
if(dataSet ==null){
getDatabaseHouseDetails();
}
myData.setValue(dataSet);
return myData;
}
//Method to actually get the data from the database
public void getDatabaseHouseDetails(){
//dataSet.add(new DecodeHouseDetails(1,1,1,"H2345","treutue.jpg","Keja Mkononi","1","A nice house","Water,electrivit","Other amenities","5","1","Embu","1","1","1","1","4345423232312","3224342434232") ); //Add data to the mutatable list
jsonObject= new JSONObject();
try {
jsonObject.put("me",""+func.getSharedUserID(mContext) );//Logged in user
} catch (JSONException e) {
Log.e("JSONObject Here", e.toString());
}
VolleyNetworkRequestInterfaceSingleton.getResponse(mContext,Request.Method.GET, URL_initializeDashboard, jsonObject,new VolleyNetworkRequestInterfaceSingleton.VolleyCallback(){
#Override
public void onSuccessResponse(String response) {
if(response!=null) {
try {
JSONObject json = new JSONObject(response);
//Successfully fetched
String sarray = json.getString("house_details");
Toast.makeText(mContext, sarray, Toast.LENGTH_SHORT).show();
JSONArray jsonArray = new JSONArray(sarray);
//Clear list to refresh list in every selection
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_list = jsonArray.getJSONObject(i);
DecodeHouseDetails houses_array = new DecodeHouseDetails(
json_list.getInt("active_identifier"),
json_list.getInt("house_id"),
json_list.getInt("house_status"),
json_list.getString("house_number"),
json_list.getString("house_cover"),
json_list.getString("house_name"),
json_list.getString("longitude"),
json_list.getString("latitude")
);
dataSet.add(houses_array);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
My ViewModel
public class GetHouseDetailsViewModel extends AndroidViewModel {
//The data we fetch from asynchronously
private MutableLiveData<List<DecodeHouseDetails>> mHouseDetailsList;
private GetHouseDetailsRepository mHouseDetailsRepository;
public GetHouseDetailsViewModel(#NonNull Application application) {
super(application);
}
public void init(){
if(mHouseDetailsList != null){
mHouseDetailsList= new MutableLiveData<>();
}
mHouseDetailsRepository = GetHouseDetailsRepository.getInstance(); //Initialize the repository
mHouseDetailsList = mHouseDetailsRepository.getHouseDetails(this.getApplication());
}
public LiveData<List<DecodeHouseDetails>> getHouseInfo() {
if(mHouseDetailsList == null){
mHouseDetailsList = new MutableLiveData<>();
}
return mHouseDetailsList;
}
}
My View - Fragment
public class AdmManageHouses extends Fragment {
private ProgressBar progressloader,progressloader_large;
SwipeRefreshLayout refreshLayout;
private TextView house_number_text,house_title_text,house_name_text;
private GetHouseDetailsViewModel mHouseDetailsViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_manage_houses, container, false);
mHouseDetailsViewModel = ViewModelProviders.of(getActivity()).get(GetHouseDetailsViewModel.class);
//Innitialize objects
house_title_text= rootView.findViewById(R.id.house_title);
house_number_text= rootView.findViewById(R.id.house_number);
house_name_text= rootView.findViewById(R.id.house_name);
//Initialize the view model
mHouseDetailsViewModel.init();
mHouseDetailsViewModel.getHouseInfo().observe(getViewLifecycleOwner(), new Observer<List<DecodeHouseDetails>>() {
#Override
public void onChanged(List<DecodeHouseDetails> decodeHouseDetails) {
for(int i=0; i<decodeHouseDetails.size(); i++) {
house_number_text.setText(String.valueOf(decodeHouseDetails.get(i).getHouse_number()));
house_title_text.setText(decodeHouseDetails.get(i).getHouse_name());
house_name_text.setText(decodeHouseDetails.get(i).getHouse_name());
}
}
});
//Refresh on swipe
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initializeDashboard();
refreshLayout.setRefreshing(false);
}
});
initializeDashboard();
return rootView;
}
private void initializeDashboard() {
for(int i=0; i<mHouseDetailsViewModel.getHouseInfo().getValue().size(); i++) {
house_number_text.setText(String.valueOf(mHouseDetailsViewModel.getHouseInfo().getValue().get(i).getHouse_number()));
house_title_text.setText(mHouseDetailsViewModel.getHouseInfo().getValue().get(i).getHouse_name());
house_name_text.setText(mHouseDetailsViewModel.getHouseInfo().getValue().get(i).getHouse_name());
}
}
}
After thorough checking of the viewmodel, I discovered that problem was in the repository and not the viewModel. I was not calling setValue() properly.
This made the first run - when the list is null - fail to populate the UI until onChange.
I made the following changes to the repository
i.e
Declare myData variable
Private MutableLiveData<List<DecodeHouseDetails>> myData= new MutableLiveData<>();
//Make a mutable list of the data that we will be getting from the database
public MutableLiveData<List<DecodeHouseDetails>> getHouseDetails(Context mContext){
this.mContext=mContext;
getDatabaseHouseDetails();
return myData;
}
//Method to actually get the data from the database
public void getDatabaseHouseDetails(){
//dataSet.add(new DecodeHouseDetails(1,1,1,"H2345","treutue.jpg","Keja Mkononi","1","A nice house","Water,electrivit","Other amenities","5","1","Embu","1","1","1","1","4345423232312","3224342434232") ); //Add data to the mutatable list
jsonObject= new JSONObject();
try {
jsonObject.put("me",""+func.getSharedUserID(mContext) );//Logged in user
} catch (JSONException e) {
Log.e("JSONObject Here", e.toString());
}
VolleyNetworkRequestInterfaceSingleton.getResponse(mContext,Request.Method.GET, URL_initializeDashboard, jsonObject,new VolleyNetworkRequestInterfaceSingleton.VolleyCallback(){
#Override
public void onSuccessResponse(String response) {
if(response!=null) {
try {
JSONObject json = new JSONObject(response);
//Successfully fetched
String sarray = json.getString("house_details");
Toast.makeText(mContext, sarray, Toast.LENGTH_SHORT).show();
JSONArray jsonArray = new JSONArray(sarray);
//Clear list to refresh list in every selection
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_list = jsonArray.getJSONObject(i);
DecodeHouseDetails houses_array = new DecodeHouseDetails(
json_list.getInt("active_identifier"),
json_list.getInt("house_id"),
json_list.getInt("house_status"),
json_list.getString("house_number"),
json_list.getString("house_cover"),
json_list.getString("house_name"),
json_list.getString("longitude"),
json_list.getString("latitude")
);
dataSet.add(houses_array);
}
myData.setValue(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
The code is working fine when testing in emulator-Android 7.1, API 25 but when I test same code in Real Device-Android 4.4.4, API 19 spinner is not showing. And there is no error message even
Config.java
public class Config {
public static String mLocation ="http://towncitycards.com/webservice_action.php?action=";
//http://towncitycards.com/webservice_action.php?action=filter_location
public static final String DATA_URL = mLocation+"filter_location";
//Tags used in the JSON String
public static final String TAG_USERNAME = "name";
public static final String TAG_NAME = "slug";
public static final String TAG_COURSE = "name";
public static final String TAG_SESSION = "slug";
//JSON array name
public static final String JSON_ARRAY = "location";
}
DemoSpinner.java
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
Please use this edited code this will work for you:
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a request queue
JsonObjectRequest StringRequest = new JsonObjectRequest(Request.Method.GET, Config.DATA_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = response;
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Volly error is this >>" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(StringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("student >>",students.toString());
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, students));
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
StringRequest stringRequest = new StringRequest(Request. Method.GET,Config.DATA_URL, new Response.Listener()
Use it in getData(). Because you wasn't specified Request.Method.GET
::OR::
You can use same like this:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "filter_location");
return params;
}
};
Then remove the parameter "action=filter_location" from url.
I am developing an application using android and i'm trying to get the jSon Array displayed in Listfragment using the loadInBackground() method below in my DataListLoader class:
class DataListLoader extends AsyncTaskLoader<List<Model>> {
List<Model> mModels;
String jsonString;
String name = "Daniel Nyerere", phone = "0652400670";
public DataListLoader(Context context) {
super(context);
loadInBackground();
}
public List<Model> loadInBackground() {
// You should perform the heavy task of getting data from
// Internet or database or other source
// Here, we are generating some Sample data
// Create corresponding array of entries and load with data.
final List<Model> entries = new ArrayList<Model>(50);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().contains("server_response")) {
jsonString = response.toString();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("name");
phone = jo.getString("user_phone");
entries.add(new Model(name, phone));
System.out.println("DATA FROM JSON ARRAY: " + name + " " + phone);
count++;
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);
entries.add(new Model(name, phone));
return entries;
}
But when i try to run it the data from System.out.println("DATA ENTRIES: "+entries); comes as null list ,so no data get displayed in the fragment activity . Anyone who can help me to fix it so that i get data from json because it consume me a lot of time
//You can call it in UI thread
final List<Model> entries = new ArrayList<Model>(5);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you need to update the `ListView` content here
//If you need you can create new thread here too e.g. using AsyncTask
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);
I've made an activity that gets jsonarray and puts it in a list. Next i've assigned an AutoCompleteTextView to a field witch fleches the json objects im using.
in my jsonarray its 3 objects: ItemID,ItemDescription and ItemVolume. My AutoCompleteTextView field contains jsonObject: ItemDescription.
I need to get the itemID when the itemDescription is selected in my onItemClickListner.
Heres the code
ArrayAdapter<String> adp = new ArrayAdapter<String>(shoppingcart.this,
android.R.layout.simple_dropdown_item_1line, responseList);
autocomplete.setAdapter(adp);
autocomplete.setThreshold(1);
private class GetContacts extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(shoppingcart.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(urlget);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
autocomplete.setThreshold(1);
try {
// Getting JSON Array from URL
AllItems = json.getJSONArray(TAG_GETALL);
for(int i = 0; i < AllItems.length(); i++) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getString(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getString(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Edit:
This is what i did for the List parts.
HashMap<String,Integer> ItemAndID= new HashMap<String,Integer>();
List<String> responseList = new ArrayList<String>();
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
AllItems = json.getJSONArray(TAG_GETALL);
for(int i = 0; i < AllItems.length(); i++) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getInt(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getInt(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
ItemAndID.put(Name, ID);
}
For OnClick I did this.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedName = (String) parent.getItemAtPosition(position);
// if you used a HashMap
ResultID = ItemAndID.get(selectedName);
}
See this example you are not saving ItemId anywhere. If you don't want to create a new Object, you can create a new list to save ItemIds or you can create a HaspMap<String, String> like ["name1":"id1","name2":"id2"] and then depending on what you use to save ItemId
setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedName = (String) parent.getItemAtPosition(position);
// if you used a HashMap
String ID = exampleHashMap.get(selectedName);
}
}
Create a new list like responseListItemId and pares it along side responseList:
List<Integer> responseListItemId = new ArrayList<Integer>();
.....
#Override
protected void onPostExecute(JSONObject json) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getString(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getString(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
responseListItemId.add(ID);
}
Now get the index value of the description from the responseList and use it in the responseListItemId to get your itemID.
My suggestion would be to create a custom class for your data type like Product and ten create a custom adapter see https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView