Sorry.... I'm new in android....
I have done such schema:
i created listview in my activity, and put on it adapter with own activity as in all tutorials...
But now i must to go further and create more complicated activity: on every my listview adapter view i must put another loop with data => other listview with adapter... Is it real?
Here is my code(i do it in education goal):
protected void onCreate(Bundle savedInstanceState) {
String bank;
bank = this.getIntent().getStringExtra("Bank_id");
url = "http://192.168.1.4:3000/exchanger_lists/get_bank_exchanger_list/"+bank+".json";
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_exchangers_list);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
banks = json.getJSONArray(TAG_Exchangers);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_address);
String location_name = c.getString(TAG_location_name);
String latitude = c.getString(TAG_latitude);
String longitude = c.getString(TAG_longitude);
String exchanger_type_name = c.getString(TAG_exchanger_type_name);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_address, address);
map.put(TAG_location_name, location_name);
map.put(TAG_latitude, latitude);
map.put(TAG_longitude, longitude);
map.put(TAG_exchanger_type_name, exchanger_type_name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_exchanger_list_element,
new String[] { TAG_NAME, TAG_location_name, TAG_address, TAG_exchanger_type_name, TAG_latitude, TAG_longitude }, new int[] {
R.id.bank_e_n, R.id.nas_punkt_e_n , R.id.adress_obm_e_n , R.id.tip_obm_e_n , R.id.shirota_e_n , R.id.dolgota_e_n });
setListAdapter(adapter);
}
i need to parse json children for each TAG_Exchangers and add in as an adapter for adapter listAdapter adapter = new SimpleAdapter(this, contactList, .......
Is it real? And how to do it?
why not using BaseAdapter , where you rule everything related to how it looks and how it uses the data? just implement getCount,getItem, and getView .
for more information about listView, watch "the world of listView" lecture.
Related
I have a list view in Main activity, I have fill some values in it by using Array Adapter
String[] arr = new String[]{"Android ListView Item 1", "Android ListView Item 2",
"Simple List View In Android", "List View onClick Event","Android List View OnItemClickListener",
"Open New Activity When ListView item Clicked", "List View onClick Source Code", "List View Array Adapter Item Click",
};
Now I want to set onclickListener to each item of the list. I am requesting an api which gives me jsonresponse and I want to iterate over jsonresponse and send required data to another activity when click item of the list.
I tried with following:
ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(this,
R.layout.activity_main2, R.id.textview, arr);
listview.setAdapter(arrayadapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String textToPass = "hello";
if (position == 0) {
Bundle passData = new Bundle();
passData.putString("data",textToPass);
Intent myIntent = new Intent(view.getContext(), Main2Activity.class);
myIntent.putExtras(passData);
startActivity(myIntent);
}
}
});
}
private String jsonParse(){
String url = "//testing/api.php"; //get json response locally
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("Item");
for(int i=0; i<=jsonArray.length();i++){
HashMap<String,String> dict = new HashMap<String,String>();
JSONObject tv = jsonArray.getJSONObject(i);
String sid;
dict.put("cid", tv.getString("sid") );
// String cid = tv.getString("sid");
String categoryName =tv.getString("category_name");
String baseUrl = "//testing/";
String imageUrl = baseUrl + tv.getString("category_image");
//textView.append(cid + "," + categoryName + "," + imageUrl + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
assert jsonArray != null;
Log.d("Main",jsonArray.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(error.getMessage(), "utf-8");
}
});
requestQueue.add(jsonObjectRequest);
Please help
If I understood properly then I think you want to send HashMap dic to another activity. HashMap are serializable this means you can easily pass it in intent, moreover both key and value are string which are also serializable
intent.putExtra("dic.key", dic);
And in your next activity retrieve it with typecasting.. simple
HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("hashMap");
hi please answer my question
i have this code in eclipse for Android Developing.
i am using mysql and php for database and get data with JSON . But i dont know how can i use JSONparse data in listview . please edit my codes.
public class ViewAllPersons extends Activity {
String url = "http://192.168.1.206/androhp/view_all_persons.php";
ArrayList<String> result;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_person);
result = new ArrayList<String>();
LoadAllPersons lap = new LoadAllPersons();
lap.execute(url);
}
class LoadAllPersons extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
InputStream jsonStream = getStreamFromURL(args[0], "GET");
String jsonString = streamToString(jsonStream);
parseJSON(jsonString);
return null;
}
void parseJSON(String JSONString) {
try {
JSONObject jo = new JSONObject(JSONString);
JSONArray allpersons = jo.getJSONArray("allpersons");
for (int i = 0; i < allpersons.length(); i++) {
JSONObject object = allpersons.getJSONObject(i);
String objString = "";
objString = object.getString("name") + " , "
+ object.getString("name2") + " : "
+ object.getInt("iconlink");
result.add(objString);
}
} catch (JSONException e) {
}
}
protected void onPostExecute(String file_url) {
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
CustomList adapter = new
CustomList(ViewAllPersons.this, web, imageUrl);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
How can I use parseJSON data instead of web listview :
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
You have got both data as well as list, now you need to combine them.
first you have to convert your json result into list, where values are your json values.
final ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listdata .add(values[i]);
}
then you have to assign adapter to your list. You can use following code.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.yourlistlayout, listdata );
list.setAdapter(adapter);
More details
http://www.vogella.com/tutorials/AndroidListView/article.html
I am developing an android application using PHP and mysql as external database. Now in my activity page whole JSON data are there but not bind in listview. I tried a lot and search on google as well.
My activity.java is below:
private void getdatalatlog(double latitude, double longitude) {
String link = "http://192.168.0.104/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'";
aq.progress(R.id.progressBar1).ajax(link, JSONObject.class, this,"jsonCallback");
}
public void jsonCallback(String link, JSONObject json, AjaxStatus status) throws JSONException {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
json = jParser.getJSONFromUrl(link);
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_MESSAGE
}, new int[] { R.id.shop_name,R.id.address,R.id.distance
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
My getdatalatlong() method is called in onCreate() method. And in jsonCallback() method's json object, I got all data of my database.
Check whether you are getting the JSON Object from the server.
if you got means do this. Store that JSON Result in an string(usually i call it JSONString).
For example :
{
"username":"Vignesh";
"title" : "Check My Site";
"content" : "vickytechy.hol.es"
}
Then use this to get the values by the index
JSONObject jsonObject = new JSONObject(JSONString);//JSONString is the JSON result;
Name = jsonObject.optString("username");//Name = Vignesh
Title = jsonObject.optString("title");//Title = Check My Site
Content = jsonObject.optString("content");//Content = vickytechy.hol.es
I have an android/java task where I want to get JSON values into a String array to display in a ListView and I am not sure where to begin? Thanks.
private String[] values;
...
// this is what is returned from the web server (Debug view)
// jObj = {"success":1,"0":"Mike","1":"message 1","2":"Fred","3":"message 2","4":"John","5":"message 3"};
try {
if (jObj.getInt("success") == 1) {
.
// what i'm trying to do here is iterate thru JObj and assign values to the
// values array to populate the ArrayAdapter so that the ListView displays this:
//
// Mike: Message 1
// Fred: Message 2
// John: Message 3
//
.
this.setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, android.R.id.text1, values));
ListView listView = getListView();
}
}
catch (JSONException e) {
Log.e(TAG, e.toString());
}
Use ArrayList instead of Array to add values retrieved from Json Obejct and then set ArrayList for ListView as data-source. change your code as:
ArrayList<String> array_list_values = new ArrayList<String>();
try {
if (jObj.getInt("success") == 1) {
array_list_values.add(jObj.getString("0"));
array_list_values.add(jObj.getString("1"));
array_list_values.add(jObj.getString("2"));
array_list_values.add(jObj.getString("3"));
array_list_values.add(jObj.getString("4"));
array_list_values.add(jObj.getString("5"));
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, array_list_values));
ListView listView = getListView();
}
}
catch (JSONException e) {
Log.e(TAG, e.toString());
}
EDIT :
if number of messages is not always the same it may 1 to a larger number then you can Iterate JsonObject as:
ArrayList<String> array_list_values = new ArrayList<String>();
try {
if (jObj.getInt("success") == 1) {
Iterator iter = jObj.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObj.getString(key);
array_list_values.add(value);
}
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, array_list_values));
ListView listView = getListView();
}
}
catch (JSONException e) {
Log.e(TAG, e.toString());
}
You should do something like that and use the awesome GSON library:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
APIResponse response = gson.fromJson(reader, APIResponse.class);
With:
Public class APIResponse{
public String 0;
public String 1;
public String 2;
public String 3;
public String 4;
public String 5;
public String succes;
}
But this won't work as you need to find an other name that 0,1,2,3,4,5 for the variables.
Please change this on server side
JSONObject jsonObject = new JSONObject(jsonString);
String value0 = jsonObject.getString("0");
or
in for loop
String tempArray[] = new String[5];
just do
for(int i=0;condition;i++){
tempArray[i] = jsonObject.getString(String.ValueOf(i));
}
and pass the array to adapter
How do I get my JSON data into my listview? All I am trying to do is loop through the JSON data and grab the first two elements and add them to my two text fields in my listview.
BUT when I do the code below it just puts the whole array element into both list views brackets and all. It increments but just the main array not the sub items. (if that makes sense)?
Below is my json data the magic happens after " //Loop the Array":
[["Ace Tattooing Co","80260","(303) 427-3522 ","461 W 84th Ave",""],["Think Tank Tattoo","80209","(720) 932-0124","172 S Broadway",""]]
This is my script so far:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowShop extends ListActivity {
private static final String TAG = "MyApp";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ziplist_layout);
Bundle bundle = getIntent().getExtras();
String shop_data = bundle.getString("shopData");
Log.v(TAG, shop_data);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
try{
//Get the element that holds the earthquakes ( JSONArray )
JSONArray jsonShopArray = new JSONArray(shop_data);
**//Loop the Array**
for(int i=0;i < jsonArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONArray e = jsonShopArray.getJSONArray(i);
Log.v(TAG, e.toString(i));
map.put("id", String.valueOf(1));
map.put("name", "Store name:" + e.toString(2));
map.put("zipcode", "Zipcode: " + e.toString(3));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.shop_list,
new String[] { "name", "zipcode" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
/**Toast.makeText(ShowShop.this, zipReturn, Toast.LENGTH_LONG).show(); */
}
}
e.toString is incorrect http://developer.android.com/reference/org/json/JSONArray.html#toString(int)
You should use getString or getInt or getWhatever