i have a lazy list that loads in a list of images at the moment the urls are hard coded in a String[] and i'm wanting to load them via a json feed. so my question is how can i create a string[] from a JsonObject?
heres what ive got so far
try {
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
fulldata = String.valueOf(json);
Log.v("myApp","newsdata" + fulldata);
newsList = new ArrayList<String>();
newsList2 = new ArrayList<String>();
newsList3 = new ArrayList<String>();
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("news");
for(int t = 0; t < newsAmount; t++){
JSONObject newsTitleDict = jArray.getJSONObject(t);
//this is where i want to load the images into a String[]
JSONArray ImageArray = objData.getJSONArray("news");
newsList3.add(newsTitleDict.getString("title"));
}
for(int t = 0; t < 1; t++){
JSONObject newsTitleDict = jArray.getJSONObject(t);
newsList.add(newsTitleDict.getString("title"));
newsList2.add(newsTitleDict.getString("title"));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
//arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3);
String[] mStrings={
"http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png",
"http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png",
"http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
"http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
};
arrayAdapter3 = new LazyAdapter(this, mStrings);
ListView list = getListView();
list.setTextFilterEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View header = inflater.inflate( R.layout.homeheader, list, false);
View header2 = inflater.inflate( R.layout.homeheader2, list, false);
View header3 = inflater.inflate( R.layout.homeheader3, list, false);
adapter = new MergeAdapter();
adapter.addView(header);
adapter.addAdapter(arrayAdapter);
adapter.addView(header2);
adapter.addAdapter(arrayAdapter2);
adapter.addView(header3);
adapter.addAdapter(arrayAdapter3);
setListAdapter(adapter);
}
This is how I add values to a String[] using an ArrayList from a JSONObject. My example uses a JSONArray, but you can always change that to fit your code.
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<String> arrayPicture = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
apiResponse = extras.getString("API_RESPONSE");
try {
JSONArray JAFriends = new JSONArray(apiResponse);
for (int i = 0; i < JAFriends.length(); i++) {
json_data = JAFriends.getJSONObject(i);
if (json_data.has("name")) {
String getFriendName = json_data.getString("name").toUpperCase();
arrayName.add(getFriendName);
} else {
String getFriendName = null;
arrayName.add(getFriendName);
}
if (json_data.has("pic_square")) {
String getFriendPhoto = json_data.getString("pic_square");
arrayPicture.add(getFriendPhoto);
} else {
String getFriendPhoto = null;
arrayPicture.add(getFriendPhoto);
}
}
} catch (JSONException e) {
return;
}
stringName = new String[arrayName.size()];
stringName = arrayName.toArray(stringName);
stringPicture = new String[arrayPicture.size()];
stringPicture = arrayPicture.toArray(stringPicture);
listofFriends = (ListView)findViewById(R.id.list);
adapter = new FriendsAdapter(this, stringName, stringPicture);
listofFriends.setAdapter(adapter);
In he for loop, using if statements to ensure no errors creep in, the returned values are added to their respective ArrayLists and 6 lines of code before the adapter is set, the values from the ArrayLists are added to the String[].
Hope this helps solve your question.
Related
Got String Data from Internal Storage.When i tried to display that data on listview only last item is displayed.
Here is my code.
listView=(ListView)findViewById(R.id.listview);
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}
Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);
}
}catch (Exception e)
{
e.printStackTrace();;
}
use final ArrayList list = new ArrayList(); before while loop
listView=(ListView)findViewById(R.id.listview);
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
final ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}
Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);
}
}catch (Exception e)
{
e.printStackTrace();;
}
i have an app where in a form show the list view. the user can click one of the list view and when clicking the app will move to another activity and it's activity will show some data based on "code" that sent from the list view form. my app is success to move in another activity but doesn't show the data. please help me.
Thank you.
This is my code in list view form :
final ListView lv = (ListView)findViewById(R.id.lv);
String url = "http://192.168.43.244/wewash/listview.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("nama", c.getString("nama"));
map.put("tanggal_keluar", c.getString("tanggal_keluar"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(halaman_utama.this, MyArrList, R.layout.listview,
new String[] {"nama", "tanggal_keluar","id", ""}, new int[] {R.id.tsnama, R.id.tstglk, R.id.kode, R.id.tsspasi});
lv.setAdapter(sAdap);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String kode = ((TextView) findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(halaman_utama.this, p_daftar_pakaian.class);
//menampilkan value dari item yg diklik
in.putExtra("id", kode);
startActivity(in);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and it's my code in new activity :
Intent intent = getIntent();
String kode = intent.getStringExtra("id");
String url = "http://192.168.43.244/wewash/listview_detail.php?id="+kode;
try {
JSONArray data = new JSONArray(getJSONUrl(url));
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String idpk = c.getString("id");
String namapk = c.getString("nama");
String paketpk = c.getString("paket");
String cbiasapk = c.getString("cbiasa");
String ckhususpk = c.getString("ckhusus");
String tglantarpk = c.getString("tanggal_keluar");
String totalpk = c.getString("total");
// String nomorpk = c.getString("no_hp");
atasnama.setText(namapk);
ereview.setText("Id Pelanggan : " +idpk+
"\nNama Pelanggan : "+namapk+
"\nPaket : "+paketpk+
"\nCucian Biasa : "+cbiasapk+" kg"+
"\nCucian Khusus : "+ckhususpk+" item"+
"\nTotal : "+totalpk+" rupiah"+
"\nTanggal Antar : "+tglantarpk);
// enomer.setText(nomorpk);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and it's the php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("wewash");
$kode=$_GET["id"];
$sql=mysql_query("select * from pakaian where id='$kode'");
$arrayId=array();
if($sql === FALSE) {
die(mysql_error());
}
while($row=mysql_fetch_array($sql)){
$arrayId["id"]=$row["id"];
$arrayId["nama"]=$row["nama"];
$arrayId["tanggal_keluar"]=$row["tanggal_keluar"];
$arrayId["paket"]=$row["paket"];
$arrayId["cbiasa"]=$row["cbiasa"];
$arrayId["ckhusus"]=$row["ckhusus"];
$arrayId["total"]=$row["total"];
}
echo json_encode($arrayId);
?>
In Android I am fetching json data from web.I the list is like {Name,dial,code}
I have this
countryinfo = new ArrayList<CountryInfo>();
Countrylist = new ArrayList<String>();
try {
for (String line : result) {
jsonarray= new JSONArray(line);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
CountryInfo conpop = new CountryInfo();
conpop.setName(jsonobject.optString("Name"));
conpop.setIso(jsonobject.optString("dial"));
conpop.setItu(jsonobject.optString("code"));
countryinfo.add(conpop);
Countrylist.add(jsonobject.optString("Name"));
}
}
} catch (Exception e) {
//Log.e("Error", e.getMessage());
e.printStackTrace();
}
I use
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MobnoAct.this, android.R.layout.simple_spinner_item, Countrylist);
mySpinner.setAdapter(adapter);
mySpinner.setSelection(0);
But in the spinner Its showing a default country name..But I want The country name will be as per locale..
like :--
Locale defaultLocale = getResources().getConfiguration().locale;
String si=defaultLocale.getCountry();
How I can do that???
Try this after you set the adapter and retrieve the default local:
for(String countryName : countryList)
for(CountryInfo country : countryinfo)
if(country.getName().equals(countryName) && country.getCode().toLowerCase().equals(si.toLowerCase()))
mySpinner.setSelection(adapter.getPosition(countryName));
Hope this helps
write Custom ArrayAdapter by example: http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
i can't fill array in cycle.
working example:
Weather weather_data[] = new Weather[]
{ new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Cloudy"),
new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Showers")
};
my code:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
You need to initialize this array:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data=new NewsData[jsonMainNode.length()];//<------------HERE
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
Simplified answer: your array is not initialized. Longer answer, you have to know how big it is going to be, then initialize it to that size. A simple example:
NewsData[] NewsData_data;
ArrayList<NewsData> newsDataArray = new ArrayList<NewsData>();
String header = "header";
String short_text = "short_text";
String team = "team";
String datatime = "datatime";
String photo_url = "photo_url";
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
NewsData_data = new NewsData[newsDataArray.size()];
newsDataArray.toArray(NewsData_data);
System.out.println(NewsData_data);
Hello i have a working code that displays a twitter timeline into a textview:
void examineJSONdata()
{
TextView tvData = (TextView) findViewById(R.id.txtData);
try
{
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++)
{
JSONObject post = entries.getJSONObject(i);
x += "------------\n";
x += "Date:" + post.getString("created_at") + "\n";
x += "Post:" + post.getString("text") + "\n\n";
}
tvData.setText(x);
}
catch (Exception je)
{
tvData.setText("Error w/file: " + je.getMessage());
}
}
Now i want to try a ListView instead of a TextView
I have found a code on StackOverFlow Android App: JSON array from web to listview
ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
JSONArray array = (JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}
I have tried to do this but I can't get i work
Would someone help convert the code with me? I think all the neccessary info is in the first code.
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray array = new JSONArray(jsontext);
String[] stringarray = new String[array.length()];
and
int i;
for (i=0;i<array.length();i++)
{
JSONObject post = array.getJSONObject(i);
String temp;
temp += "Date:" + post.getString("created_at") + "\n";
temp += "Post:" + post.getString("text");
stringarray[i]=temp;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);