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
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.
Hey guys I know this is a common problem, Im using a AsyncTaskActivity to have a JSON parser parse some json behind the scences of a app and pump a listview with an arrayadapter. This is my code code in my mainActivity.java. My screen flickers whenever I get to the belwo activity.
setContentView(R.layout.activity_see_schedule_activity);
this.setTitle("Activity Schedule");
//Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
RequestQueue queue = Volley.newRequestQueue(see_schedule_activity.this);
StringRequest request = new StringRequest(Request.Method.POST, httpUpdateRoutines, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(see_schedule_activity.this, "" + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(see_schedule_activity.this, "Data Not Fetched " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
//Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
map.put("residentid", getIntent().getExtras().getString("id#"));
return map;
}
};
queue.add(request);
new AsyncTaskParseJson(this).execute();
ArrayList<String> schedulelist = getIntent().getExtras().getStringArrayList("tasks_filled");
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, schedulelist);
ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter);
My AsyncTaskparseJson.java
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
private Context c;
String schedule;
String activityid;
String routine;
String[] tasks;
ArrayList<String> schedulelist = new ArrayList<String>();
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.wirelesshealth.wayne.edu/nhcheckup/getData(justin).php";
// contacts JSONArray
JSONArray dataJsonArr = null;
public AsyncTaskParseJson(Context applicationContext) {
this.c=applicationContext;
}
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
-----------------------some hash -----------------
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("schedule");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
Log.e("doInBackground","YOU GOT HERE");
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
activityid = c.getString("activityid");
-------------------------------Pasres object c --------------
}
Intent intent = new Intent(c,see_schedule_activity.class);
-- passes back arraylist -------------- intent.putStringArrayListExtra("tasks_filled",schedulelist);
this.c.startActivity(intent);
((Activity)c).finish();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
// Intent intent = new Intent(see_schedule_activity.this,see_schedule_activity.class);
// intent.putExtra("tasks_filled",tasks);
// this.c.startActivity(intent);
// ((Activity)c).finish();
}
}
I did a bit of troubleshotting and found out the error has to do with the placement of the intent that's passed a array list. But here's the problem, if I put it in the doinBackground() the screen flashes rapidly (which is prolly becuase it keeeps calling the (setContentView(R.layout.activity_see_schedule_activity);) but if I keep it in onPostExcute nothing happens (hte arraylist isnt pumping the listview). So im a bit stumped, any help would be appreciated thanks!
As I said in my comment, you enter a recursive call between the activity and the AsyncTask as you start the same activity again with an Intent. Instead, as you already pass the activity instance to the AsyncTask, simply create an update method in the activity and use that from the AsyncTask:
// field in see_schedule_activity
private ArrayAdapter<String> adapter;
// which you'll initialize in onCreate()
// with an empty list, as you don't yet have the data
...
adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, new ArrayList<>());
ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter);
... rest of onCreate()
public void update(List<String> results) {
adapter.clear();
adapter.addAll(results);
}
Then implement correctly the AsyncTask:
public class AsyncTaskParseJson extends AsyncTask<String, Void, List<String>> {
private see_schedule_activity activity;
//... the rest
public AsyncTaskParseJson(see_schedule_activity activity) {
this.activity = activity;
}
#Override
protected List<String> doInBackground(String... arg0) {
// create scheduleList
return scheduleList;
}
#Override
protected void onPostExecute(List<String> results) {
activity.update(results);
}
//...
This is not a good implementation of the AsyncTask but should get you going.
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.
i want to make listview where the listview data only coming from the name of "windy",from my json file. can someone tell me where's my error ?
i make a condition in my json array to put in listview.
it should be show all the data from json and put it in the listview because (x == y) is right, but nothing happen , only empty listview.
when i make System.out.println(x +" "+ y); to make sure there's no empty, it show the value of x and y that is windy and windy, and from the condition i make it should show the the listview only the name of windy. but when i make (x!= y) it show all the data from json to listview.
thank you so much guys.
this is the part code of my conditian i make.
for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);
String x = ar.getString("nama");
String y = "windy";
System.out.println(x +" "+ y);
//the conditon that i mean.
//when i make if(x!=y), it show all the data from json to listview, not only "windy"
if( x == y){
HashMap<String, String> map = new HashMap<String, String>();
String nama = ar.getString("nama");
String judul = ar.getString("judul");
String komen = ar.getString("komen");
String jawaban = ar.getString("jawaban");
String created_at = ar.getString("created_at");
map.put(tanya_nama, nama);
map.put(tanya_judul, judul);
map.put(tanya_komen, komen);
map.put(tanya_jawaban, jawaban);
map.put(tanya_waktu, created_at);
data_map.add(map);
this is the full code.
public class semuatempat extends ListActivity {
static String tanya_nama = "nama";
static String tanya_judul = "judul";
static String tanya_komen = "komen";
static String tanya_jawaban = "jawaban";
static String tanya_waktu = "created_at";
JSONArray str_json = null;
public String lo_Koneksi,isi ;
// Search EditText
EditText inputSearch;
//Listview Adapter
SimpleAdapter adapter;
ListView lv;
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> data_map = new ArrayList<HashMap<String, String>> ();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.utama);
Koneksi lo_Koneksi = new Koneksi();
isi = lo_Koneksi.isi_koneksi();
new AmbilData().execute();
}
class AmbilData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(semuatempat.this);
pDialog.setMessage("loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String link_url = isi+"komentar.php";
JSONParsena jParser = new JSONParsena();
JSONObject json = jParser.AmbilJson(link_url);
try {
str_json = json.getJSONArray("komentar");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
/**
* Hashmap to load data from the Sqlite database
**/
HashMap<String,String> user = new HashMap<String, String>();
user = db.getUserDetails();
for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);
String x = ar.getString("nama");
String y = "windy";
System.out.println(x +" "+ y);
if( x == y){
HashMap<String, String> map = new HashMap<String, String>();
String nama = ar.getString("nama");
String judul = ar.getString("judul");
String komen = ar.getString("komen");
String jawaban = ar.getString("jawaban");
String created_at = ar.getString("created_at");
map.put(tanya_nama, nama);
map.put(tanya_judul, judul);
map.put(tanya_komen, komen);
map.put(tanya_jawaban, jawaban);
map.put(tanya_waktu, created_at);
data_map.add(map);
}
else{
System.out.println(" cacad ");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
semuatempat.this, data_map,
R.layout.list_item, new String[] { tanya_nama, tanya_judul, tanya_komen,tanya_jawaban,tanya_waktu},
new int[] {R.id.nama, R.id.alamat, R.id.lat,R.id.lng,R.id.waktu});
setListAdapter(adapter);
}
});
Problem is with the string compare function you have written :
x == y
Replace this with:
if (x.equals(y))
as x and y are strings.
Change your
if( x == y)
to
if( x.equals(y)) because you are comparing String.
Then in your AsyncTask, maybe you should change,
class AmbilData extends AsyncTask(String, String, String)
to
class AmbilData extends AsyncTask(String, String, HashMap<String, String>) {
In method doInBackground
protected String doInBackground(String... args) {
// rest of your method
return map;
}
Change onPostExecute method to:
protected void onPostExecute(HashMap<String,String> map) {
// adapting your hashmap to listview
}
I've not tested it yet. But, it should work.
Can anyone help here. I'm trying to populate a listview from a json response. the response is posting, for some reason it isn't showing the list? anything helps
Also it is stopping on the list view, just not seeing anything.
extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> ideasList;
// url to get all products list
private static String url_all_products = "http://theideavault.no-ip.org//android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ideas";
private static final String TAG_IID = "iid";
private static final String TAG_NAME = "idea";
// products JSONArray
JSONArray ideas = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_idea);
// Hashmap for ListView
ideasList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String iid = ((TextView) view.findViewById(R.id.iid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditIdeaActivity.class);
// sending pid to next activity
in.putExtra(TAG_IID, iid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllIdeasActivity.this);
pDialog.setMessage("Reteiving Ideas from database. Wooooooo...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Ideas: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
ideas = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < ideas.length(); i++) {
JSONObject c = ideas.getJSONObject(i);
// Storing each json item in variable
String iid = c.getString(TAG_IID);
String idea = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_IID, iid);
map.put(TAG_NAME, idea);
// adding HashList to ArrayList
ideasList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewIdeaActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllIdeasActivity.this, ideasList,
R.layout.list_idea, new String[] { TAG_IID,
TAG_NAME},
new int[] { R.id.iid, R.id.idea });
// updating listview
setListAdapter(adapter);
}
});
}
}}
The great mistake you did is while initialize TAG_PRODUCTS variable.
Mistake:
private static final String TAG_PRODUCTS = "ideas";
Correct value:
private static final String TAG_PRODUCTS = "products";
BTW, are you fetching ideas or products? because your response is of products and your code describes Idea :)