json file not being read - java

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());

Related

I want to pass the string that I got from the string to the onPostExecute method

I am New to the android studio and want to something more. Actually, I am trying to pass the string that I got from the spinner in onCreateMethod and pass to the onPostExecute function. I will be grateful for the help. Bellow is my code.
I tried making a global variable called First and store the string from spinner and pass it on the onPostExecute function.
public class Convert extends AppCompatActivity implements LocationListener
{
Spinner dropdown;
Button btn;
String text;
String first;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
dropdown = (Spinner) findViewById(R.id.spinner1);
btn = (Button)findViewById(R.id.btn);
String[] items = new String[]{"United States,USD", "Nepal,NPR", "Bangladesh,BDT","Brazil,BRL"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text = dropdown.getSelectedItem().toString();
first = text.substring(text.length()-3);
Log.i("her", first);
}
});
new DownloadTask().execute("http://openexchangerates.org/api/latest.json?
app_id=XXXXXXXXXX");
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char counter = (char) data;
result += counter;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
JSONObject jsonObject = new JSONObject(result);
JSONObject curr = jsonObject.getJSONObject("rates");
String npr = curr.getString(first);
Log.i("money", npr );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
What I want is to pass the string first on the onPostExecute function.
When you will call your DownloadTask, asyncTask fires with method execute, just pass param though him. Example:
How to pass url
new DownloadTask().execute("url for download");
How to receive url
protected String doInBackground(String... urls) {
String url = urls[0]; // url for download
}
Also you could send and array of params. Also be careful with AsyncTask, do not pass your context/view variable, it could arise memory leaks, read docs.

Parsing a Json array witout array name

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

ListView shows no items from database

I tried many ways but I got blank layout.I changed lots of lines but the result is always the same. Should I rewrite the code and try something different. I followed some videos on youtube but nobody has the proper solution.I don't think it is caused because array got null result. Anybody knows what might be wrong:
AirportTransportActivity
public class AirportTransportActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data = new String[0];
JSONObject jsonObject = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
//Adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}
In your original post you have set the adapter before you have added the data. But I also suspect that you are having issues with:
String[] data = new String[0];
So I changed it to
ArrayList<String> data = new ArrayList<>();
I also changed your AsyncTask a bit. Now you can do most of your parsing in the background thread. When the doInBackground is successful just notify the adapter of the changes in onPostExecute.
You will also need to check if the ArrayList<String> fits to your Adapter class. If not just change it as needed.
Do this instead:
public class AirportTransportActivity extends AppCompatActivity {
private static final String TAG = AirportTransportActivity.class.getSimpleName();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return toString();
}
#Override
protected void onPostExecute(String result) {
if(result.isEmpty()) return;
try{
ArrayList<String> data = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
JSONArray jsonArray = new JSONArray(result);
int len = jsonArray.length();
Log.e(TAG, "Lenth of json array = " + len)
for (int i = 0; i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// I add the optString variation just in case the data is corrupt
String s = jsonObject.optString("airporttransportname", "?");
data.add(s);
}
listView.setAdapter(adapter);
}
catch(JSONException e){
e.printStackTrace();
}
}
}
Disclaimer I did this in a text editor and wasn't able to count on "auto-correct" for some of the syntax or method names--so you will need to check it.
There are some other things I would change in your code, but I wanted to leave it as close to the original as I could.
You're setting the data array and calling notifyDataSetChanged() before your async task has a chance to finish. You need to set your adapter and notifyDataSetChanged() from within the onPostExecute() method in your async task.
Just to be clear, when you call asyncTask.execute(), it starts the async task and then immediately keeps executing the rest of the code. So when you set your data array in your list view adapter, the asyncTask hasn't even finished and your array items are still null.
No need to change anything just add adapter.notifyDataSetChanged(); after storing all values into your array
Remove this line adapter.notifyDataSetChanged();in Oncreate ,You
have to use notifyDataSetChanged() when your arraylist values is getting
changed.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}

extract data from PHP json to use in android

I'm using this code to fetch some data from PHP file and extract some data into my android application.
This code extract name, price and availability for each product and put each one in an String.
Now I need to have array of the product in java which that is included name,price and availability for each product and name them product1 product2 product3 so I'll be able to write rest of my code based on that.
How can I do that ?
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view.findViewById(R.id.name)).getText().toString();
String selval1 = ((TextView) view.findViewById(R.id.price)).getText().toString();
String selval2 = ((TextView) view.findViewById(R.id.found)).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval", selval);
intnt.putExtra("selval1", selval1);
intnt.putExtra("selval2", selval2);
startActivity(intnt);
}
});
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
its very simple, by using this code outside of the for loop
JSONObject pro1 = jsonMainNode.getJSONObject(0);

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