Parsing a Json array witout array name - java

LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data;
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;
String x, y;
public Graph_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_graph_, container, false);
}
HttpURLConnection connection;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
graph = (GraphView) getView().findViewById(R.id.graph1);
//graphDataClass gdc = new graphDataClass();
//gdc.execute();
String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\"," +
"\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";
String data = "";
try {
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float salary = Float.parseFloat(jsonObject.optString("salary").toString());
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
}
graphOneTV.setText(data);
} catch (JSONException e) {e.printStackTrace();}}}
So I was trying to parse JSON array by using the above code and it worked but later I was trying to fetch the JSON from my localhost pc but that JSON is not having a array name. The json which i am trying to fetch is given below.
[{"twitter":"200","googleplus":"60"},{"twitter":"150","googleplus":"180"},{"twitter":"90","googleplus":"120"}]
The code for fetching and parsing this JSON array is given below.
LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data,data2;
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;
//String x, y;
public Graph_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_graph_, container, false);
}
HttpURLConnection connection;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
graph = (GraphView) getView().findViewById(R.id.graph1);
graphDataClass gdc = new graphDataClass();
gdc.execute();
/*String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\"," +
"\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";
String data = "";
try {
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float salary = Float.parseFloat(jsonObject.optString("salary").toString());
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
}
graphOneTV.setText(data);
} catch (JSONException e) {e.printStackTrace();}
*/
}
public class graphDataClass extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL("http://192.168.1.34/getGraphData.php?");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jsonRootObject = new JSONObject(data);
JSONArray jsonArray = jsonRootObject.optJSONArray("");
for(int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int x = Integer.parseInt(jsonObject.optString("twitter").toString());
int y = Integer.parseInt(jsonObject.optString("googleplus").toString());
data2 += "Node" + i + " : \n id= " + x + " \n Name= " + y ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
graphOneTV.setText(data2);
}
}
}
But as is said earlier this JSON is not having a array name, so what should I write a the place where array name is required.
JSONArray jsonArray = jsonRootObject.optJSONArray("What show I write HERE ???? (No Array Name in JSON!!!");

modify the php code file
<?php
if($connect){
die('Could Not Connect :'.mysqli_error());
}
$result = mysqli_query($connect,"SELECT * FROM table_name);
while($row=mysqli_fetch_assoc($result)){
$output[]=$row;
}
print(json_encode(array('yourarrayname' =>$output),JSON_PRETTY_PRINT));
mysqli_close($connect);
?>
JSONArray jsonArray = jsonRootObject.optJSONArray("yourarrayname_define_php_json_file");

I Hope this will work for you.
parse like this.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String twitter = jsonObject.getString("twitter");
String googleplus = jsonObject.getString("googleplus");
Log.e("googleplus", googleplus);
Log.e("twitter", twitter);
}
} catch (Exception e) {
}
And add data to arraylist.

If you know your string is a JSON array, then parse the string with JSONArray instead of JSONObject. Then use the array accessors like JSONArray.get.
JSONArray jsonArray = new JSONArray(json);
JSONObject first = jsonArray.optJSONObject(0);
Otherwise use gson:
Type collectionType = new TypeToken<Collection<Map<String, Object>>>(){}.getType();
Collection<Map<String, Object>> items = gson.fromJson(json, collectionType);
Or jackson:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>();
List<Map<String, Object>> items = new ObjectMapper().readValue(json, typeReference);

Try this way :
ArrayList<HashMap<String, String>> arrayListSocial = new ArrayList<>();
String string = "[{\"twitter\":\"200\",\"googleplus\":\"60\"},{\"twitter\":\"150\",\"googleplus\":\"180\"},{\"twitter\":\"90\",\"googleplus\":\"120\"}]";
try {
JSONArray jsonarray = new JSONArray(string);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String socailTwiter= jsonobject.getString("twitter");
String socailGplus = jsonobject.getString("googleplus");
Log.e("socailTwiter",socailTwiter);
HashMap<String, String> hashMap = new HashMap<>();
hashMap .put("twitter",socailTwiter);
hashMap .put("googleplus",socailGplus );
arrayListSocial.add(hashMap);
}
}catch (Exception e){
e.printStackTrace();
}

Related

json file not being read

I have an app that is supposed to read a json file and inset its contents into a list view, I know this question was asked tons of times here but I can't understand why it's not working. I managed to narrow my problem to 1 line so far, JSONObject object = new JSONObject(readJSON());. This is all of my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Post> arrayList;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvPosts);
arrayList = new ArrayList<>();
try {
JSONObject object = new JSONObject(readJSON());
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String productName = jsonObject.getString("productName");
String locationName = jsonObject.getString("locationName");
String price = jsonObject.getString("price");
String date = jsonObject.getString("date");
String description = jsonObject.getString("description");
String comment = jsonObject.getString("comment");
Log.i(TAG, price);
Post post = new Post();
post.setItemName(productName);
post.setLocationName(locationName);
post.setPrice(price);
post.setDate(date);
post.setDescription(description);
post.setExistingComment(comment);
arrayList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
PostAdapter adapter = new PostAdapter(this, arrayList);
listView.setAdapter(adapter);
}
public String readJSON() {
String json = null;
try {
// Opening data.json file
InputStream inputStream = getAssets().open("MOCK_DATA.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
// read values in the byte array
inputStream.read(buffer);
inputStream.close();
// convert byte to string
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
My problem is that once I run the app my listView will remain empty and wont be populated with data.
if you are using java version >jdk1.7 then I would recommend you use Files class from "java.nio.file" package . you can easily read JSON file in a single line code.
public String readJSON() {
String jsontext="";
try{
jsontext= new String(Files.readAllBytes(Paths.get("<file path>"),StandardCharset.UTF_8);
}
catch(Exception ex){
ex.printStackTrace();
}
return jsontext;
}
after that you can use JSONObject to parse string like below:---
JSONObject object = new JSONObject(readJSON());

Iteration of strings inside my arraylist to textview not working

Hi I want to set the text of my textview according the the data i got from my arraylist from my JSONObject. But my app stops working when i try to iterate my arraylist to my textview. Can you guys help me with my problem. Thaaanks! Here is my code. Thanks
AsyncClass taskSpecialty = new AsyncClass(DetailActivity.this, postData, false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d("DetailAcitivty", s);
try {
JSONObject parentObject = new JSONObject(s);
JSONArray parentArray = parentObject.getJSONArray("result");
StringBuffer finalBufferedData = new StringBuffer();
for (int i=0 ; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
String spcltID = finalObject.getString("sName");
finalBufferedData.append(spcltID + "\n");
}
ArrayList<String> listdata = new ArrayList<String>();
for(int i =0; i<parentArray.length(); i++){
listdata.add(parentArray.getString(i));
}
LinearLayout llSpecialty = (LinearLayout) findViewById(R.id.llSpecialty);
Iterator<String> iterator = listdata.iterator();
while (iterator.hasNext()){
TextView textView = new TextView(DetailActivity.this);
textView.setText(listdata.get(1));
llSpecialty.addView(textView);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
taskSpecialty.execute("http://10.0.2.2/wingman/specialty.php");
You need to call iterator.next() in while loop.
textView.setText(iterator.next());
You can do it as following:
String str="";
while (iterator.hasNext()){
TextView textView = new TextView(DetailActivity.this);
str+=iterator.next();
llSpecialty.addView(textView);
}
textView.setText(str);

How extract JSONObject from JSONArray in android

I want to read only the "value" object from this jsonarray
"body":{"und":[{"value":"hi friends!!!","summary":null,"format":null}]}
This is my code:
protected void onPostExecute(final JSONObject result) {
try {
TextView lst2 = (TextView) findViewById(R.id.View2);
JSONArray cast = result.getJSONArray("body");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("value");
lst2.setText(name);
}
} catch (Exception e2) {
Log.v("Error adding article", e2.getMessage());
}
}
JSONObject result is the response from the rest server.
body is not array its object, you need to get und out of body as JSONArray first
protected void onPostExecute(final JSONObject result) {
try {
TextView lst2 = (TextView) findViewById(R.id.View2);
JSONArray cast = result.getJSONObject("body").getJSONArray("und");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("value");
lst2.setText(name);
}
} catch (Exception e2) {
Log.v("Error adding article", e2.getMessage());
}
}
Hope it helps

Json to hashMap listview

I'm new to android development. Can you please help me to put my code to the hashmap-listview? Here I am loading bank images to the ListView. in my new JSON there is a key and value. ie (BankName , logo)
public void ListDrwaer() {
List<String> listImg = new ArrayList<String>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
listImg.add(test1);
Log.d("URL", test1);
}
ItemsAdapter adapter = new ItemsAdapter(getActivity(), listImg);
menu.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
}
You can use Pairs instead of HashMap
Try this
public void ListDrwaer() {
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
String BankName = jsonChildNode.optString("id");
listData.add(new Pair<String,String>(BankName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
}

how to parse json output from mysql

I have a google map inside my android application, I have some saved data in mysql db with latitude and longitude and i want to read that data from mysql db.
I have wrote code but the app is still error .
myphp is :
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('joe', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT lattitude, longitude FROM tracking";
$result = mysql_query($query, $link) or die('Errorquery: '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$data = "{joel:".json_encode($rows)."}";
echo $data;
?>
I have 3 java activities
public class lagiiiiteslagi extends ListActivity {
private static String url = "http://10.0.2.2/labiltrack/daftartracking.php";
// JSON Node names
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
// contacts JSONArray
JSONArray lattitude = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 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
lattitude = json.getJSONArray(TAG_lattitude);
// looping through All Contacts
for(int i = 0; i < lattitude.length(); i++) {
JSONObject c = lattitude.getJSONObject(i);
// Storing each json item in variable
String lattitude = c.getString(TAG_lattitude);
String longitude = c.getString(TAG_longitude);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_lattitude, lattitude);
map.put(TAG_longitude, longitude);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e){
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.main,
new String[] { TAG_lattitude, TAG_longitude }, new int[] {
R.id.TextViewResult, R.id.TextViewResult1 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
// getting values from selected ListItem
//String lattitude = ((TextView)) view.findViewById(R.id.TextViewResult)).getText().toString();
//String longitude = ((TextView)) view.findViewById(R.id.TextViewResult1)).getText(lattitude).toString();
String lattitude = ((TextView) view.findViewById(R.id.TextViewResult)).getText().toString();
String longitude = ((TextView) view.findViewById(R.id.TextViewResult1)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_lattitude, lattitude);
in.putExtra(TAG_longitude, longitude);
startActivity(in);
}
});
}
}
this JSONparser class :
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser(){
}
public JSONObject getJSONFromUrl(String url) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
this is use to display in listview :
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String lattitude = in.getStringExtra(TAG_lattitude);
String longitude = in.getStringExtra(TAG_longitude);
// Displaying all values on the screen
TextView lbllattitude = (TextView) findViewById(R.id.listlat);
TextView lbllongitude = (TextView) findViewById(R.id.listlong);
lbllattitude.setText(lattitude);
lbllongitude.setText(longitude);
}
}
I just want to display that lattitude and longitude in listview but still error, I'm new to android, I hope some one help me,
Thank in advance !
check this link for json help...
I suggest to to use log like Log.e("JSON", json); in different place to find the point where the error actually happens.

Categories