Json array with null values - android

I have trouble with a JSON array, and I really hope there is someone who can help me.
Lets say I have a class with JSON data and I'm sending "intent putextra" to another activity.
How can I change the value of null before I send it to another activity? I did a few prints to discover the null values and they are different, example :
Monday : null
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
**and so on.**
The problem is that --> I have all json data and I parsing them into objects, but I would like to before "intent.putextra" and send them to another activity finds null and replace them with "Closed"
so it will look like
Monday : Closed
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
EDIT
public class LocationBased extends ListActivity{
// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";
private static final String TAG = "Debug of Project"; //
private String a;
private String b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");
String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
Cursor cursor = db.rawQuery(query, null);
if(cursor != null)
{
cursor.moveToFirst();
a = cursor.getString(0);
b = cursor.getString(1);
}
String url = "http://webservice.XXX.XX/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";
Log.d(TAG, "Leyth URL = Lat : " + a +" Long : " + b);
// now enabled if disabled = ingen support for jb aka 4.0
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
try {
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
String location_id = c.getString(TAG_Location);
String company_id = c.getString(TAG_Company);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String place = c.getString(TAG_PLACE);
String postal = c.getString(TAG_POSTAL);
String city = c.getString(TAG_CITY);
String monday = c.getString(TAG_MONDAY);
String tuesday = c.getString(TAG_TUESDAY);
String wednesday = c.getString(TAG_WEDNESDAY);
String thursday = c.getString(TAG_THURSDAY);
String friday = c.getString(TAG_FRIDAY);
String saturday = c.getString(TAG_SATURDAY);
String sunday = c.getString(TAG_SUNDAY);
String type = c.getString(TAG_TYPE);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
String nocar = c.getString(TAG_NOCAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_Location, location_id);
map.put(TAG_Company, company_id);
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_PLACE, place);
map.put(TAG_POSTAL, postal);
map.put(TAG_CITY, city);
map.put(TAG_MONDAY, monday);
map.put(TAG_TUESDAY, tuesday);
map.put(TAG_WEDNESDAY, wednesday);
map.put(TAG_THURSDAY, thursday);
map.put(TAG_FRIDAY, friday);
map.put(TAG_SATURDAY, saturday);
map.put(TAG_SUNDAY, sunday);
map.put(TAG_TYPE, type);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
map.put(TAG_NOCAR, nocar);
// Log.d(TAG, "Leyth Days = Mandag : " + monday +" Onsdag : " + wednesday);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_LAT, TAG_LNG, TAG_POSTAL }, new int[] {
R.id.name, R.id.email, R.id.mobile });
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<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String mandag = ((TextView) view.findViewById(R.id.mandag)).getText().toString();
String tirsdag = ((TextView) view.findViewById(R.id.tirsdag)).getText().toString();
String onsdag = ((TextView) view.findViewById(R.id.onsdag)).getText().toString();
String torsdag = ((TextView) view.findViewById(R.id.torsdag)).getText().toString();
String fredag = ((TextView) view.findViewById(R.id.fredag)).getText().toString();
String lordag = ((TextView) view.findViewById(R.id.lordag)).getText().toString();
String sondag = ((TextView) view.findViewById(R.id.sondag)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name);
in.putExtra(TAG_LNG, cost);
in.putExtra(TAG_Company, description);
in.putExtra(TAG_MONDAY, mandag);
in.putExtra(TAG_TUESDAY, tirsdag);
in.putExtra(TAG_WEDNESDAY, onsdag);
in.putExtra(TAG_THURSDAY, torsdag);
in.putExtra(TAG_FRIDAY, fredag);
in.putExtra(TAG_SATURDAY, lordag);
in.putExtra(TAG_SUNDAY, sondag);
startActivity(in);
}
});
}
}

I am also suffering for this problem in past but i do not know this is good solution but it works for me. Hope it is usefull to you also.
String jsonObject_string ;
try {
if (jsonObject != null) {
// ur stuff when not null
}
} catch (Exception e) {
// TODO: handle exception
// when null it automatic fill value
jsonObject_string = "Closed";
}

As I understand you want to replace any null string with a specific string , say "Closed".
This doesn't have anything todo with JSON, if this were my code I would do a simple check before adding those values to my intent. the code will look something like this:
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name == null ? "Closed" : name);
in.putExtra(TAG_LAT, cost== null ? "Closed" : cost);
in.putExtra(TAG_Company, description == null ? "Closed" : description );
in.putExtra(TAG_MONDAY, mandag == null ? "Closed" : mandag);
....
And so on.
name == null ? "Closed" : name ;
Simple asks if name is null then the value is closed, else return name.
it is the same as :
if (name == null){
in.putExtra(TAG_LAT, "Closed");
} else {
in.putExtra(TAG_LAT, name);
}
I hope that is what you're looking for

Why not try to replace all null strings in the JSON as a string before you parse the JSON file/object?
Possible other solution could be looping through every object checking if they're null. then replacing that for Closed
EDIT:
Load the JSON object as a string and then replace all null to Closed like this:
String JSON = JsonObject.toString();
JSON.replace("null", "Closed");
EDIT 2:
add this below JSONArray json = jParser.getJSONFromUrl(url);:
String s = json.toString(); // converts json object to string
json.replace("null", "Closed"); // replaces null for Closed
JSONArray json = new JSONArray(s); // converts back to json object

if(c.getString(TAG_MONDAY!=null && c.getString(TAG_MONDAY).length>0 && !(c.getString(TAG_MONDAY).equals("")))
{
String monday=c.getString(TAG_MONDAY);
}
else
{
String monday="Closed";
}

Related

how to turn two sqlite tables into a JSON object

Is it possible to turn a two table(relational tabel) from sqlite in to a JSON object? I've googling but still cannot find a way to convert those table. So far, i've only manage to turn one table into JSON object. If it's possible, can you tell me how to do it? if it's not, can you give me an alternatives? thanks.
here's the code that turn one table to JSON object:
private JSONArray getResults()
{
Context context = this;
String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to database
String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString() );
Intent pass_data = new Intent(this,BluetoothOut.class);
pass_data.putExtra("pindah",resultSet.toString());
startActivity(pass_data);
return resultSet;
}
}
And this is my table in my DatabaseHelper :
//tabel order
public static final String ORDER_TABLE_NAME="tb_order";
public static final String COL_1="ORDERID";
public static final String COL_2="USERID";
public static final String COL_3="PASSWORD";
public static final String COL_4="MEJA";
public static final String COL_5="TOPUP";
public static final String COL_6="SALDO";
//tabel lineitems
public static final String LINEITEMS_TABLE_NAME="tb_lineitems";
public static final String COL1 = "FOODID";
public static final String COL2 = "PRICE";
public static final String COL3 = "NUM";
public static final String COL4 = "RES";
public static final String COL6 = "ORDERID_FK";
table line items and orderid related to each other where orderid in tb_order as PK and orderid_fk in tb_lineitems as FK.
A good way to export data from your database is to use Gson, which is Google's Json serialization/deserialization library.
Fetch your Objects from your database like normally, and then use Gson to convert it into Json and export it.
Here is an example of how you could do it.
private void exportDatabase() {
// Create an instance of Gson.
Gson gson = new Gson();
// You can easily convert Objects into Json.
MyItem item = new MyItem();
String json = gson.toJson(item);
// Fetch your items from your database.
ArrayList<MyItems> items = database.getAll();
// Arrays are a bit harder to convert, but not very.
json = gson.toJson(items, new TypeToken<ArrayList<MyItems>>(){}.getType());
// Now export it to some easily copy-pasted location.
System.out.println(json);
}

list view with single contact activity in android

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
String price =((TextView) view.findViewById(R.id.price)).getText().toString();
String amount=((TextView) view.findViewById(R.id.mobile_labels)).getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_PHONE_MOBILE,description);
//in.putExtra(TAG_PHONE_HOME,price);
// in.putExtra(TAG_PHONE_OFFICE,amount);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
contact.put(TAG_PHONE_OFFICE,office);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME,TAG_PHONE_OFFICE }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.price ,R.id.mobile_labels});
setListAdapter(adapter);
}
}
}
Here is the list. In this I am getting name,email and mobile number. In the list when I select a name in the list open a new activity in that activity I need name, email, phone, address, gender, office. How should I pass this in next activity.
Here is the next activity code.
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
String office= in.getStringExtra(TAG_PHONE_OFFICE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
TextView lblOffice = (TextView) findViewById(R.id.mobile_office);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
lblOffice.setText(office);
}
}
It's better if I have only a name in the listview. On selecting the name in the list further details should be displayed, for instance: name, phone, email, address, gender.
Pass them through the intent you used to start the new activity. When you generate the intent you can bundle some information and pass it as an extra. Then all the information should be in the bundle when your new activity starts. That's probably the easiest way.
There's lots of information in those links, and google has tutorials on how to use intents as well.
Hope that helps!

listview on select the item in list display a detail activity

private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
// String description = ((TextView) view.findViewById(R.id.mobile))
//.getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.home });
setListAdapter(adapter);
}
}
}
I have a list activity in the list it display the name,email,phone number on select an item in the list open a new activity and display the same name, email,number but i need others details in nextactivity including addrees,gender,home, office
In the nextactivity i displaying this items
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
}
Inclusignthsi i want to display address,home,office .
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
#subhas i have updated th other activity code

After selected listitem shows the details of them on another activity through json?

I have activity in which I show the list item and in list item I only want to show the name of places and I am able to show it but when I click on the item I want related to that place name it shows the detail on another activity i.e. location detail. so please help me to resolve my problem I am new in android.
here is my both activity code:
locationList=( ListView)findViewById(R.id.list_Surroundings);
// Hashmap for ListView
ArrayList<HashMap<String, String>> locationOfList = new ArrayList<HashMap<String, String>>();
adapter = new SimpleAdapter(this, locationOfList,
R.layout.list_item1,
new String[] { TAG_NAME }, new int[] {
R.id.name});
locationList.setAdapter(adapter);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Category
location=json.getJSONArray(TAG_LOCATION);
//looping through all categories
for(int i = 0; i < location.length(); i++){
JSONObject c = location.getJSONObject(i);
JSONObject c1=c.getJSONObject(TAG_LOCATION1);
// Storing each json item in variable
String LocationID = c1.getString(TAG_LOCATION_ID);
String Name = c1.getString(TAG_NAME);
String Phone = c1.getString(TAG_PHONE);
String FormattedPhone = c1.getString(TAG_FORMATTED_PHONE);
String Address = c1.getString(TAG_ADDRESS);
String CrossStreet = c1.getString(TAG_CROSS_STREET);
String Lat = c1.getString(TAG_LAT);
String Lng = c1.getString(TAG_LNG);
String Distance = c1.getString(TAG_DISTANCE);
String PostalCode = c1.getString(TAG_POSTAL_CODE);
String City = c1.getString(TAG_CITY);
String State = c1.getString(TAG_STATE);
String Country = c1.getString(TAG_COUNTRY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_LOCATION_ID, LocationID);
map.put(TAG_NAME, Name);
map.put(TAG_PHONE, Phone);
map.put(TAG_FORMATTED_PHONE, FormattedPhone);
map.put(TAG_ADDRESS, Address);
map.put(TAG_CROSS_STREET, CrossStreet);
map.put(TAG_LAT, Lat);
map.put(TAG_LNG, Lng);
map.put(TAG_DISTANCE, Distance);
map.put(TAG_POSTAL_CODE, PostalCode);
map.put(TAG_CITY, City);
map.put(TAG_STATE, State);
map.put(TAG_COUNTRY, Country);
// adding HashList to ArrayList
locationOfList.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
locationList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// getting values from selected ListItem
String Name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String Distance = ((TextView) view.findViewById(R.id.distance_list1)).getText().toString();
String Country = ((TextView) view.findViewById(R.id.country_list1)).getText().toString();
String City = ((TextView) view.findViewById(R.id.city_list1)).getText().toString();
String Phone = ((TextView) view.findViewById(R.id.phone_list1)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), LocationDetails.class);
in.putExtra(TAG_NAME, Name);
in.putExtra(TAG_DISTANCE, Distance);
in.putExtra(TAG_COUNTRY, Country);
in.putExtra(TAG_CITY, City);
in.putExtra(TAG_PHONE, Phone);
startActivity(in);
}
});
public class LocationDetails extends Activity{
// JSON node keys
private static final String TAG_NAME = "Name";
private static final String TAG_PHONE = "Phone";
private static final String TAG_ADDRESS = "Address";
private static final String TAG_DISTANCE= "Distance";
private static final String TAG_CITY = "City";
private static final String TAG_COUNTRY= "Country";
private TextView name,phone,address,distance,city,country;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_details);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String Name = in.getStringExtra(TAG_NAME);
String Phone = in.getStringExtra(TAG_PHONE);
String Address = in.getStringExtra(TAG_ADDRESS);
String Distance = in.getStringExtra(TAG_DISTANCE);
String City = in.getStringExtra(TAG_CITY);
String Country = in.getStringExtra(TAG_COUNTRY);
// Displaying all values on the screen
name= (TextView) findViewById(R.id.TxtView_name);
phone=(TextView)findViewById(R.id.TxtView_PhoneField);
address=(TextView)findViewById(R.id.TxtView_AddressField);
distance=(TextView)findViewById(R.id.TxtView_DistanceField);
city=(TextView)findViewById(R.id.TxtView_CityField);
country=(TextView)findViewById(R.id.TxtView_CountryField);
name.setText(Name);
phone.setText(Phone);
address.setText(Address);
distance.setText(Distance);
city.setText(City);
country.setText(Country);
}
}
In sending activity, try replacing
in.putExtra(TAG_NAME, Name);
in.putExtra(TAG_DISTANCE, Distance);
in.putExtra(TAG_COUNTRY, Country);
in.putExtra(TAG_CITY, City);
in.putExtra(TAG_PHONE, Phone);
with
Bundle extras = new Bundle();
extras.putString(TAG_NAME, Name);
extras.putString(TAG_DISTANCE, Distance);
extras.putString(TAG_COUNTRY, Country);
extras.putString(TAG_CITY, City);
extras.putString(TAG_PHONE, Phone);
extras.putExtras(extras);
In receiving activity, try replacing
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String Name = in.getStringExtra(TAG_NAME);
String Phone = in.getStringExtra(TAG_PHONE);
String Address = in.getStringExtra(TAG_ADDRESS);
String Distance = in.getStringExtra(TAG_DISTANCE);
String City = in.getStringExtra(TAG_CITY);
String Country = in.getStringExtra(TAG_COUNTRY);
with
Bundle extras = getIntent().getExtras();
if(extras != null) {
String Name = extras.getString(TAG_NAME);
String Phone = extras.getString(TAG_PHONE);
String Address = extras.getString(TAG_ADDRESS);
String Distance = extras.getString(TAG_DISTANCE);
String City = extras.getString(TAG_CITY);
String Country = extras.getString(TAG_COUNTRY);
}
You are trying to get the data from the TextViews, which is not at all right.
You need to fetch the values of the selected item from the ArrayList by using locationOfList(position) inside the onClick() of the listItem.
Something like this :
locationList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// getting values from selected ListItem
HashMap<String, String> selectedMap = locationOfList.get(position);
// Starting new intent
Intent in = new Intent(getApplicationContext(), LocationDetails.class);
in.putExtra(selectedMap);
startActivity(in);
}
});
And in your second Activity, use this example to retrieve the data from the HashMap.

Endless listview not loading items

I am using listview to display items obtained from json response. Currently 10 items are displaying, as i scroll down more items must load but it is not happening. Following is my code can anyone help me? Answers will be appreciated.
public class MainActivity extends ListActivity {
ListView list;
LazyAdapter adapter;
JSONArray posts;
// All static variables
static final String URL = "http://site.org/";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONArray posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
adapter.notifyDataSetChanged();
ListView list=(ListView)findViewById(android.R.id.list);
list.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String content = ((TextView) view.findViewById(R.id.content)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),SampleDesp.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_CONTENT, content);
startActivity(in);
}
});
list.setOnScrollListener(new OnScrollListener(){
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
});
}
}

Categories

Resources