Android: JSON and ListView's quickest refresh options? - java

I have the following class:
public class RandomDrunkQuotes extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("uDrew Debug", "Made it into onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("uDrew Debug", "main Layout Loaded");
//Add AdMob viewer
AdView adViewer = (AdView)this.findViewById(R.id.adViewer);
adViewer.loadAd(new AdRequest());
Log.i("uDrew Debug", "Calling getServerData");
//Get Server Data and handle
getServerData();
}
public static final String KEY_121 = "http://www.url.com/android.php"; //i use my real ip here
private void getServerData() {
//Declare variables
InputStream is = null;
String result = "";
String strQuote = "";
String strID = "";
String strFName = "";
String strLInitial = "";
String strCity = "";
String strState = "";
String strDate = "";
Integer intLikes = 0;
Integer intHates = 0;
String strFNameSaid = "";
String strLInitialSaid = "";
Integer intBuzz = 0;
String strBuzzed = "";
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
Log.i("uDrew Debug", "Declared variables");
//Declare inflater in order to inflate a layout for each quote
LinearLayout l = (LinearLayout) findViewById(R.id.myMainLayout);
LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/android.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
Log.i("uDrew Debug", "Trying to Parse JSON Data");
//Place JSON data into array one item at a time
JSONArray jArray = new JSONArray(result);
//Loop through each record in the database
//Get ListView
ListView lv= (ListView)findViewById(R.id.listview);
// create the grid item mapping
String[] from = new String[] {"lblQuote", "lblBuzzed", "lblShared", "lblSaid", "lblLikes", "lblHates", "lblLocation", "lblDate"};
int[] to = new int[] { R.id.lblQuote, R.id.lblBuzzed, R.id.lblShared, R.id.lblSaid, R.id.lblLikes, R.id.lblHates, R.id.lblLocation, R.id.lblDate };
for(int i=0;i<jArray.length();i++){
Log.i("uDrew Debug", "Made it into JSONArray Loop");
//Get this record
JSONObject json_data = jArray.getJSONObject(i);
//Put each result into variables for later handling
strFName = json_data.getString("FName");
strLInitial = json_data.getString("LInitial");
strCity = json_data.getString("City");
strState = json_data.getString("State");
strDate = json_data.getString("Date");
strQuote = json_data.getString("Quote");
intLikes = Integer.parseInt(json_data.getString("Likes"));
intHates = Integer.parseInt(json_data.getString("Hates"));
strFNameSaid = json_data.getString("FNameSaid");
strLInitialSaid = json_data.getString("LInitialSaid");
intBuzz = Integer.parseInt(json_data.getString("Buzz"));
Log.i("uDrew Debug", "Made it past JSON Parsing");
switch(intBuzz){
case 1:
strBuzzed = ("One Beer\nSyndrome");
break;
case 2:
strBuzzed = ("Buzzed");
break;
case 3:
strBuzzed = ("Drunk");
break;
case 4:
strBuzzed = ("Trashed");
break;
case 5:
strBuzzed = "Retarded";
break;
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("lblQuote", strQuote);
map.put("lblBuzzed", strBuzzed);
map.put("lblShared", strFName + " " + strLInitial);
map.put("lblSaid",strFNameSaid + " " + strLInitialSaid);
map.put("lblDate", strDate);
map.put("lblLocation", strCity + ", " + strState);
map.put("lblLikes", intLikes.toString());
map.put("lblHates", intHates.toString());
fillMaps.add(map);
}//End For loop
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.myviews, from, to);
lv.setAdapter(adapter);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
I'd like to know how to refresh the data retrieved from the server in the quickest fashion. Right now I have an Refresh button in the options button that calls getServerData(); but this seems to take a very long time. Any thoughts are welcome.

You should create an AsyncTask and call getServerData() method from its doInBackground() method. This method must return the data from the server. Then in onPostExecute() method you should populate the ListView with this data.

Related

JSON respone in list view display based on the particular condition in android

I need to display the items on particular condition .I done that one.I have three tabs are present.In the first tab A ,i display the list of items,in that only one item is present.But when you move to tab B and again come to tab A,we can see two items.I need to avoid that repeating item displaying, how to do that one, please help me if you have an idea,Thank you in advance
Here is my code:
List View list;
ListViewAdapter adapter;
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> title_array1 = new ArrayList<String>();
ArrayList<String> title_array2 = new ArrayList<String>();
ArrayList<String> title_array3 = new ArrayList<String>();
ArrayList<String> title_array4 = new ArrayList<String>();
ArrayList<String> title_array5 = new ArrayList<String>();
ArrayList<String> title_array6 = new ArrayList<String>();
String response_value;
JSONObject result;
JSONArray tokenList;
JSONObject oj5;
String appid;
JSONObject oj;
String fileid;
HttpEntity entity;
String status ,borrowername,coborrowername,loannumber,addrs1,city;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_frame, container, false);
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
new AsyncTaskParseJson().execute();
return rootView;
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "******");
object.put("Password", "******");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("*********");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
entity = response.getEntity();
response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value);
if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);
JSONArray tokenList = result.getJSONArray("Files");
}
} catch (Exception e) {
e.printStackTrace();
}
return response_value;
}
#Override
protected void onPostExecute(String response_value) {
super.onPostExecute(response_value);
// dismiss the dialog after getting all products
try
{
if (entity != null) {
result = new JSONObject(response_value);
tokenList = result.getJSONArray("Files");
for(int i=0;i<=tokenList.length();i++)
{
oj = tokenList.getJSONObject(i);
String oj1 = oj.getString("FileID");
JSONObject oj12= (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
fileid = oj.getString("FileID");
borrowername = oj12.getString("FirstName");
coborrowername = oj2.getString("FirstName");
loannumber = oj3.getString("LoanNumber");
addrs1 = oj4.getString("Address1");
city = oj4.getString("City");
JSONArray orders = oj.getJSONArray("Orders");
for(int n=0;n<orders.length();n++){
JSONObject oj5 = orders.getJSONObject(n);
appid = oj5.getString("ApplicationOrderId");
String duedate = oj5.getString("DueDate");
status = oj5.getString("Status");
// Log.e(TAG, appid +"/"+ appid1);
Log.e(TAG, appid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber + fileid );
if(status.equals("1")){
title_array3.add("New");
title_array1.add(addrs1 + " ,"+ city);
title_array.add(borrowername +" , "+coborrowername);
title_array2.add("Duedate");
// title_array3.add(status);
title_array4.add(appid);
title_array5.add(loannumber);
title_array6.add(fileid);
list.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent first = new Intent(getActivity(),DetailView.class);
first.putExtra("fileid", fileid);
startActivity(first);
} });
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), title_array,title_array1,title_array2,title_array3,title_array4,title_array5,title_array6);
list.setAdapter(adapter);
}
}
}

Dynamically adding Groups and Headers to an Expandable List View

I have data coming in as a JSON Array and I am parsing it. Here is an example:
[{"Tag":"Amusement Parks","Category":"Attractions"},{"Tag":"Restaurant","Category":"Food"}, etc]
What I want to do is to make every "Category" a Header in the ListView and every "Tag" a child of that Header. Right now I am hard coding the Header's and adding the Tags like this:
listDataHeader.add("Attractions");
listDataHeader.add("Food");
listDataHeader.add("Lodging");
...
JSONArray jArray = new JSONArray(result);
Log.d("Array Length: ", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
if (json.getString("Category").equals("Attractions")) {
tempAttractions.add(json.getString("Tag"));
}
if (json.getString("Category").equals("Food")) {
tempFood.add(json.getString("Tag"));
}
if (json.getString("Category").equals("Lodging")) {
tempLodging.add(json.getString("Tag"));
}
}
}
protected void onPostExecute(Void... params) {
listDataChild.put(listDataHeader.get(0), tempAttractions);
listDataChild.put(listDataHeader.get(1), tempFood);
listDataChild.put(listDataHeader.get(2), tempLodging);
But instead of hard coding the categories, I want to dynamically add categories from the JSON data.
So basically, something like this...
//obviously pseudo code...
if (json.getString("Category") exists as a header already) {
add json.getString("Tag") as a child under that group
//or if it doesn't exist
} else {
add a header header and add json.getString("Tag") as a child under that group
}
I think this is more of a conceptual problem, I can't seem to grasp a way to get this done. Any ideas? Thanks!
Full Code
public class CategorySelect extends BaseActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
List<String> listAttractions;
List<String> listFood;
List<String> listLodging;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_select);
// initialize Nav Drawer
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
progress = new ProgressDialog(this);
progress.setMessage("Loading...Please Wait");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Attractions");
listDataHeader.add("Food");
listDataHeader.add("Lodging");
listAttractions = new ArrayList<String>();
listFood = new ArrayList<String>();
listLodging = new ArrayList<String>();
new FillCategories().execute();
}
private class FillCategories extends
AsyncTask<Integer, Void, Void> {
List<String> tempAttractions = new ArrayList<String>();
List<String> tempFood = new ArrayList<String>();
List<String> tempLodging = new ArrayList<String>();
#Override
protected ArrayList<Location> doInBackground(Integer... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String action = "nav";
nameValuePairs.add(new BasicNameValuePair("action", action));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
Log.d("Array Length: ", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
//Log.d("Text", json.getString("Txt"));
if (json.getString("Cat").equals("Attractions")) {
tempAttractions.add(json.getString("Txt"));
if (json.getString("Tag").equals(null)) {
tempAttractionsTags.add(json.getString("Txt"));
} else {
tempAttractionsTags.add(json.getString("Tag"));
}
}
if (json.getString("Cat").equals("Food")) {
tempFood.add(json.getString("Txt"));
if (json.getString("Tag").equals(null)) {
tempFoodTags.add(json.getString("Txt"));
} else {
tempFoodTags.add(json.getString("Tag"));
}
}
if (json.getString("Cat").equals("Lodging")) {
tempLodging.add(json.getString("Txt"));
if (json.getString("Tag").equals("")) {
tempLodgingTags.add(json.getString("Txt"));
Log.d("Tag", "Is Null");
} else {
tempLodgingTags.add(json.getString("Tag"));
Log.d("Tag Not Null", json.getString("Tag"));
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
protected void onPostExecute(Void... params) {
listDataChild.put(listDataHeader.get(0), tempAttractions);
listDataChild.put(listDataHeader.get(1), tempFood);
listDataChild.put(listDataHeader.get(2), tempLodging);
}
}
}
You can do something like this
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
if (listDataChild.get(json.getString("Category")) == null) {
tempList = new ArrayList<String>();
tempList.add(json.getString("Tag"));
listDataChild.put(json.getString("Category"), tempList );
}else{
tempList = listDataChild.get(json.getString("Category"));
tempList.add(json.getString("Tag"));
listDataChild.put(json.getString("Category"), tempList );
}
You can use this library : library, it is very simple and very efficient

Android : Convert List Array to String Array show nothing

I am trying to get the data from URL and convert it into String Array, but when I try to show it on TextView its show nothing. The link and itemId that I use is already right.
There's no Error warning on logcat.
I can't figure it out why.
Is there anyone can't help me?
Here's my json data
[{"image":"http://cdn-data.apps.com/category_item/05d92b217f916c9b9d87ab9121662d87.jpg"},
{"image":"http://cdn-data.apps.com/category_item/0424ef5a980255ff989fe5b20eaa5dcd.jpg"},
{"image":"http://cdn-data.apps.com/category_item/02b5bce4a9ca8fa3e53ceea2c7e273ff.jpg"},
{"image":"http://cdn-data.apps.com/category_item/dd15419113c091c93eafb3695eb65153.jpg"},
{"image":"http://cdn-data.apps.com/category_item/1ddfd2d7a489678e3c66e7f012ceb951.jpg"}]
Here's my Java code
if(in.getStringExtra("TAG_IMAGE_COUNT").equals("0")) {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.GONE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.GONE);
}
else {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.VISIBLE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.VISIBLE);
try {
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String json = reader.readLine();
//JSONObject jsonObject = new JSONObject(json);
JSONArray arr = new JSONArray(httpResponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
String[] stringArr = list.toArray(new String[list.size()]);
TextView array = (TextView)findViewById(R.id.testarray);
array.setText(Arrays.toString(stringArr));
Log.d("", json);
//Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I try to show it on testarray but its show nothing.
First of all your have to parse a String not Httpresponse:
here you do:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
JSONArray arr = new JSONArray(httpResponse);
Change a little like:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
And finally set the list data as you want in your textView out of the background thread.
you should not use any UI thread views (e.g button, textview, edittext ..) in background thread.
EDIT:
private class GetImages extends AsyncTask<String, Integer, ArrayList<String>>{
ArrayList<String> list = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(String... params) {
try {
HttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
//use this result and put in your textView
}
}

How to Parse URL with JSON object -Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
i have the URL (.com) which has the JSON object .. i created the JSON object using PHP and uploaded in a server so it will be dynamically updated (similar to RSS). I face two problems the first one shows error " and of type java.Lang.String cannot be converted to JSON object" so i used this code and the error goes:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// 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;
}
}
The SingleMenuItemActivity calss:
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_Title = "Title";
private static final String TAG_Date = "Date";
#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 name = in.getStringExtra(TAG_Title);
String description = in.getStringExtra(TAG_Date);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
lblName.setText(name);
lblCost.setText(description);
}
}
The AndroidJasonParsingActivity calss:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://www.rssparser.host22.com/";
// JSON Node names
private static final String TAG_NAME = "Title";
private static final String TAG_Image = "Image";
private static final String TAG_Category = "Category";
private static final String TAG_Venue = "Venue";
private static final String TAG_Date = "Date";
// contacts JSONArray
JSONArray contacts = null;
#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
//contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String Image = c.getString(TAG_Image);
String Category = c.getString(TAG_Category);
String Venue = c.getString(TAG_Venue);
String Date = c.getString(TAG_Date);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_Date);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_Image, Image);
map.put(TAG_Date , Date );
// 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.list_item,
new String[] { TAG_NAME, TAG_Date }, 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();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_Date, description);
startActivity(in);
}
});
}
}
first create JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// 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;
}
}
then create activity
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// 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;
#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
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin 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);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// 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.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, 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();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
and write Internet permission in manifest file
this is best tutorial

Android: Remove null values from an array:

How can I remove any null values from an array.
public class RecipeMethodActivity extends ListActivity {
Intent myIntent;
String value;
TextView editvalue;
TextView buttonPressed;
Intent intent;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result2 = null;
final Recipe[] mRecipesArray = { new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
if(!recipes[i].name.equals(value)){
recipes[i].steps = null;
Recipe[] tmp = new Recipe[recipes.length - 1];
//int j = 0;
//for (int k = 0; k < recipes.length; k++) {
// if (j != 1) {
// tmp[j++] = recipes[i];
// }
//}
recipes = tmp;
} else {
ret.add(recipes[i].name);
}
}
return ret;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
value = getIntent().getStringExtra("searchValue");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_name=json_data.getString("recipename");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, MethodActivity.class);
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
it returns a list view which when clicked should take you to the matching recipe but if i ask for Earth Destruction I get the portal cake recipe methods.
Thanks
This line of code is a problem
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
Instead of using mRecipesArray[position] use ret.get(position).steps
and declare ArrayList<Recipe> ret = new ArrayList<Recipe>(); outside of the FetchRecipesRawArray() method so that it can be accessed inside onListItemClick() method.
also modify your code in FetchRecipesRawArray()
else {
ret.add(recipes[i]);
}
Hope this will help you..

Categories

Resources