I currently have this code with the purl.getString("url") containing url links to jpg images online. I would like to display these images in a list or grid but cannot understand how. The current code simply lists all of the URLs in listview but just want those URL's to be their respective images.
Here is my code
public class BreadActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.fetchJsonStuff()));
}
public ArrayList<String> fetchJsonStuff()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL example = new URL(
"http://api.tumblr.com/v2/blog/example.tumblr.com");
URLConnection tc = example.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONObject ob = new JSONObject(line);
JSONObject object = ob.getJSONObject("response");
JSONArray ja = object.getJSONArray("posts");
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
JSONArray nja = (JSONArray) jo.getJSONArray("photos");
for (int i1 = 0; i1 < nja.length(); i1++) {
JSONObject njo = (JSONObject) nja.get(i1);
JSONObject purl = (JSONObject) njo.getJSONObject("original_size");
listItems.add(purl.getString("url"));
}
}
}
} catch (MalformedURLException 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();
}
return listItems;
}
}
Related
I want to convert this program to dynamic. Get JSON from server and return to list item.
public List<Item> getData() {
return Arrays.asList(
new Item(1, "Everyday" , "$12.00 USD"),
new Item(2, "Small Porcelain Bowl", "$50.00 USD"),
new Item(3, "Favourite Board", "$265.00 USD"),
);
}
I parsed the json but return type error.
Error:(73, 8) error: incompatible types: List<String> cannot be converted to List<Item>
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
Information:BUILD FAILED in 13s
Information:2 errors
Here my code:
List<String> listItems = new ArrayList<String>();
try {
URL arc= new URL(
"https://arc.000webhostapp.com/data/Cse.json");
URLConnection tc = arc.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException 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();
}
return listItem;
You've declared that your function will return a List of Item objects but instead you're returning a List of String objects. When parsing the JSON you get from the server you must turn it into the same Item objects like you did in the offline version of your code.
Judging by your code the JSON that you download from the server looks something like this:
[
{
id: 1,
text: "Everyday",
price: "$12.00 USD"
},
{
id: 2,
text: "Small Porcelain Bowl",
price: "$50.00 USD"
},
{
id: 3,
text: "Favourite Board",
price: "$265.00 USD"
},
]
Your function should then look something like this:
public List<Item> getData() {
List<Item> listItems = new ArrayList<Item>();
try {
URL arc= new URL(
"https://arc.000webhostapp.com/data/Cse.json");
URLConnection tc = arc.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(new Item(jo.getInt("id"), jo.getString("text"), jo.getString("price")));
}
}
} catch (MalformedURLException 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();
}
return listItems;
}
Here is the code i had tried with multiple times to get multiple rows values in a single text view with json.
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("survey_textresponse"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hiding progress bar after done loading TextView.
progressbar.setVisibility(View.GONE);
}
}
}
when i run php file in chrome directly it shows all values from database while in android app it shows only the first row value.
Because you are only storing the last value of JSONobject in json reference
// assume JArray length = 5
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
// only have last object value , in last iteration jArray.getJSONObject(4)
}
There can be many solutions to this
Collect data as list of Values
Collect in a String or StringBuilder Object
StringBuilder sb = new StringBuilder();
// or List<String> list = new ArrayList<>();
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
sb.append(json.optString("survey_textresponse")+"\n");
// or list.add(json.optString("survey_textresponse"));
}
and later
textview.setText(sb.toString());
// or can collect list as string using loop and display it
The loop that you've written for retrieving the values from the JSONArray is not proper. Its only storing the last object while iterating through the loop. You could store the retrieved values in a collection of string.
Here's an example code you could follow:
private class RetrieveTask extends AsyncTask<Void,Void,Void>{
List<String> jsonResults;
String str;
JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonResults=new ArrayList<>();
}
#Override
protected void onPostExecute(Void aVoid) {
for(String data:jsonResults)
textview.append(data);
}
#Override
protected Void doInBackground(Void... voids) {
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
if(json.optString("survey_textresponse")!=null){
jsonResults.add(json.getString("survey_textresponse"));
}
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Your json variable contains only last element of JsonArray when it is finished. You can display on TextView while retrieving your values from JsonArray.
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
textview.setText(textview.getText() + json.getString("survey_textresponse") + "\n");
}
I want to parse text and image from a json on file in asset folder to my listview. Please explain clearly because I am biginner in android. Give me complete codes of all files. Thank you a lot.
Just open the file from the assets folder like this
StringBuilder buf=new StringBuilder();
InputStream json;
try {
json = context.getAssets().open("YOUR_FILE_NAME.txt");
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;
while ((str=in.readLine()) != null) {
buf.append(str);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
result1 = buf.toString();
result1 will have the complete json from your file
then use this library called Gson to parse the json ...
Here is the tutorial for it Json parsing through Gson
Maybe code can help you.
public class MainActivity extends Activity {
private ListView listView;
private void log(String msg) {
Log.d("DNB", this.getClass().getName() + ">>" + msg);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.listView = new ListView(this);
String jsonData = loadJsonFromAsset();
String[] items = parseJson(jsonData);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
setContentView(listView);
log("json from asset: " + jsonData);
}
private String[] parseJson(String jsonData) {
String[] items = new String[0];
if (jsonData != null) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
if (jsonArray != null) {
items = new String[jsonArray.length()];
for (int i = 0; i < items.length; i++) {
items[i] = jsonArray.get(i).toString();
}
}
} catch (JSONException e) {
log("err--" + e.toString());
}
}
return items;
}
private String loadJsonFromAsset() {
InputStream stream;
try {
stream = getBaseContext().getAssets().open("json_list.txt");
if (stream != null) {
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
if (buffer != null) {
return new String(buffer);
}
}
} catch (IOException e1) {
log("err--" + e1.toString());
}
return "";
}
And json file at assets
["item line 1","item line 2","item line 3"]
here my code for fetching values from web api. in my code no error is there. but in emulator doesn't show the values. please tell me where i done a mistake. let me know what is the correct code for that.
public class MainActivity extends ActionBarActivity {
Spinner sp1;
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=<random number>&action=Get Cities";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp1=(Spinner)findViewById(R.id.spinner1);
}
public class Mysync extends AsyncTask<List<String>, List<String>, List<String>>{
#Override
protected List<String> doInBackground(List<String>... arg0) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url1);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
//Log.e(TAG,e.toString());
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
try {
list.add(arr.getJSONObject(i).getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
protected void onPostExecute(List<String> result){
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
}
}
public String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
// Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
}
Define List under the line
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=&action=Get Cities";
like : List<String> list ;
And Try to Change the line
List list = new ArrayList();
Via
list = new ArrayList();
and Change
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
Via
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item,result);
Hope this may help you!
I am parsing json from the following url
http://www.kaverisoft.com/careers/assignments/android/a1.php
with the following code
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter(
this,android.R.layout.simple_list_item_1,
this.populate()));
}
private ArrayList<String> populate() {
ArrayList<String> items = new ArrayList<String>();
try {
URL url = new URL
("http://www.kaverisoft.com/careers/assignments/android/a1.php");
HttpURLConnection urlConnection =
(HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// gets the server json data
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String next;
while ((next = bufferedReader.readLine()) != null){
JSONArray ja = new JSONArray(next);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
items.add(jo.getString("text"));
}
}
} catch (MalformedURLException 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();
}
return items;
}
}
The logcat shows that org.json.JSONException value text not found
but i am not able to populate any data to listview,but if i use direct json format url i can get data populated please help.
the output is like the image below.
Please help me solve this .
As far as I can see, you have 3 kinds of objects in the list: camera, book and music.
For each of them you'll have to use different parsing. First you should detect what kind of objects the current element of the array is.
For example:
if (jo.has("book")) {
JSONObject jsonBook = jo.getJSONObjcejt("book");
// continue with parsing book stuff
} else if (jo.has("camera"){
// same, but for camera
} else if (jo.has("music") {
// same, but for music
}
Then you can populate the list with books, music and camera object you parsed.
If you want smarter parsing, have a look at gson.