List item to list view - android

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;
}

Related

Multiple rows data in single textview android

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");
}

check whether json object contains json array or not?

In my json response I getting json array and inside it there are 80 other json object and in each object has elements and some of objects has JsonArray also. So how can I check that whether json array is present or not?
I have tried optjsonarray also but it did not work for me.
Here is my code:
public static void insertMyDiaryValues(final JSONObject jobject)
throws Throwable {
String arrOfColumn[] = new String[] { "uuid", "date", "title", "diary",
"pictureurl", "pictureWidth", "pictureHeight", "child" };
try {
SmartTable DiaryData = null;
DiaryData = SmartApplication.REF_SMART_APPLICATION.getDataHelper()
.getTableList().get(DBTblNames.MyDiaryValues);
try {
JSONArray jarr = new JSONArray(jobject.getJSONArray("diary"));
for (int i = 0; i < jarr.length(); i++) {
// String childValue = ""
// + jarr.getJSONObject(i).getJSONArray("child").length();
// System.out.println("child Value :-"
// + jarr.getJSONObject(i).getJSONArray("child").length());
// if (!(childValue == null)) {
DiaryData.insertRow(
arrOfColumn,
new String[] {
jarr.getJSONObject(i).get("uuid")
.toString(),
jarr.getJSONObject(i).get("date")
.toString(),
jarr.getJSONObject(i).get("title")
.toString(),
jarr.getJSONObject(i).get("diary")
.toString(),
jarr.getJSONObject(i).get("pictureurl")
.toString(),
jarr.getJSONObject(i).get("pictureWidth")
.toString(),
jarr.getJSONObject(i).get("pictureHeight")
.toString(),
""
+ jarr.getJSONObject(i)
.getJSONArray("child")
.length()
});
}
} catch (Exception e) {
}
}
catch (Exception e) {
// TODO: handle exception
}
}
Simply check using try-catch case :
try{
JSONArray jsonArray = jsonObject.getJSONArray("key");
}catch (JSONException e){
e.printStackTrace();
// here write your code to get value from Json object which is not getJSONArray.
}
The below code worked for me :-
public static void insertMyDiaryValues(final JSONObject jobject) {
String arrOfColumn[] = new String[] { "uuid", "date", "title", "diary",
"pictureurl", "pictureWidth", "pictureHeight", "child" };
try {
SmartTable DiaryData = null;
DiaryData = SmartApplication.REF_SMART_APPLICATION.getDataHelper()
.getTableList().get(DBTblNames.MyDiaryValues);
JSONArray jarr = new JSONArray(jobject.getJSONArray("diary")
.toString());
for (int i = 0; i < jarr.length(); i++) {
String child;
if (jarr.getJSONObject(i).has("child")) {
child = ""
+ jarr.getJSONObject(i).getJSONArray("child")
.length();
} else {
child = "0";
}
try {
DiaryData.insertRow(arrOfColumn,
new String[] {
jarr.getJSONObject(i).get("uuid")
.toString(),
jarr.getJSONObject(i).get("date")
.toString(),
jarr.getJSONObject(i).get("title")
.toString(),
jarr.getJSONObject(i).get("diary")
.toString(),
jarr.getJSONObject(i).get("pictureurl")
.toString(),
jarr.getJSONObject(i).get("pictureWidth")
.toString(),
jarr.getJSONObject(i).get("pictureHeight")
.toString(), child
});
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
} catch (Exception e) {
// TODO: handle exception
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

fetching the values from web api to andorid spinner

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!

Append data in Json file

I have this type of JSON:
{
"stampi":
[
{
"nome": "Ovale Piccolo 18.2x13.5cm",
"lunghezza": 18.2,
"larghezza": 13.5,
"altezza": 4,
"volume": 786.83
},
{
"nome": "Ovale Grande 22.5x17.4cm",
"lunghezza": 22.5,
"larghezza": 17.4,
"altezza": 4,
"volume": 1246.54
}
]
}
and normally I read with this code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
and after use the array inside the program.
I have create a menu that add new value inside the JSON file but i have a problem ...this is the code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjson_stampi);
// Creating JSONArray from JSONObject
JSONArray objNames = jsonObjMain.names();
System.out.println(objNames.toString());
jsonArray_stampi = jsonObjMain.getJSONArray("stampi");
int num_elem = jsonArray_stampi.length();
jsonObjMain.put( "nome","prova");
jsonObjMain.put( "lunghezza",22);
jsonObjMain.put( "larghezza", 10);
jsonObjMain.put( "altezza", 4);
jsonObjMain.put( "volume", 10.5);
jsonArray_stampi.put( jsonObjMain );
try {
FileWriter file = new FileWriter("c:\\test.json");
//file.write(jsonArray_stampi.);
file.write( JSON.stringify(jsonArray_stampi) );
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} });
why can't work correctly?
the num_elem variable are 2 always..help me!
thx Andrea
You have to create a new JSONObject and then add new data to it and then append to the existing object.
JSONObject jsonObjMain = new JSONObject(myjson_stampi); //Your existing object
JSONObject jO = new JSONObject(); //new Json Object
JSONArray jsonArray_stampi = jsonObjMain.getJSONArray("stampi"); //Array where you wish to append
//Add data
jO.put( "nome","prova");
jO.put( "lunghezza",22);
jO.put( "larghezza", 10);
jO.put( "altezza", 4);
jO.put( "volume", 10.5);
//Append
jsonArray_stampi.put(jO);
Also you should write back the complete jsonObject back to the file.
file.write(JSON.stringify(jsonObjMain));
Looks like you're trying to write to a file called c:\\test.json. Try using the proper Android way to write to files with openFileOutput. Examples are here.
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

Android using JSON url to load images in List

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;
}
}

Categories

Resources