Android Open Source - FoodFinderApp Async View Requests






From Project

Back to project page FoodFinderApp.

License

The source code is released under:

GNU General Public License

If you think the Android project FoodFinderApp listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package cs499.examples.semesterproject;
//  w w  w  . j  ava2  s .c  o m
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class AsyncViewRequests extends AsyncTask <String, String, JSONArray>
{
  List<NameValuePair> pairs;
  ListView lv;
  ViewRequests context;
  String url;
  ProgressDialog progressDialog;
  String[] requests;
  
  public AsyncViewRequests (List <NameValuePair> pairs, ListView lv, ViewRequests context, String url)
  {
    this.pairs = pairs;
    this.lv = lv;
    this.context = context;
    this.url = url;
  }
  
  protected void onPreExecute() 
  {
    // TODO Auto-generated method stub
    progressDialog = new ProgressDialog(context);
      progressDialog.setMessage("Fetching requests...");
        progressDialog.show();  
    }
    

  @Override
  protected JSONArray doInBackground(String... params) 
  {
    // TODO Auto-generated method stub
    for (int i = 0; i < pairs.size(); i++)
    {
      Log.d(pairs.get(i).getName() + ": ", pairs.get(i).getValue());
    }
      return this.getJSONFromUrl(this.url);
  }
  
  public JSONArray getJSONFromUrl(String url)
  {
    // Making HTTP request
        InputStream is = null; 
        String json = null;
        JSONArray jObj = null;
          try {
              // defaultHttpClient
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost post = new HttpPost(url);
              post.setEntity(new UrlEncodedFormEntity(pairs));
              HttpResponse httpResponse = httpClient.execute(post);
              HttpEntity httpEntity = httpResponse.getEntity();
              is = httpEntity.getContent();           

          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }

          try {
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              StringBuilder sb = new StringBuilder();
              int value=0;
              int count = 0;
               
               // reads to the end of the stream 
              value = br.read();
               while( value != -1)
               {
                  // converts int to character
                  char c = (char)value;
                  sb.append(c);
                  count++;
                  //System.out.println(c);
                  value = br.read();
               }
              is.close();
              String s = sb.toString();
              System.out.println("Characters read: "+count+", Length of S: "+s.length());
              json = s;
              System.out.println("getJSONfromURL: "+ json);
          } catch (Exception e) {
              Log.e("Buffer Error", "Error converting result " + e.toString());
          }
          

          // try parse the string to a JSON object
          try {
              jObj = new JSONArray(json);
          } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
          }

          // return JSON String
          return jObj;
  }
  
   protected void onPostExecute (JSONArray jobj)
    {
     if (this.progressDialog.isShowing())
       this.progressDialog.dismiss();
     this.showQueryResults (jobj);
    }
   
    public void showQueryResults (JSONArray j)
     {
       ArrayList<HashMap<String, String>> requestsList = new ArrayList<HashMap<String, String>>();
      try
      {
        JSONArray docs = j;
            
              for(int i = 0; i < docs.length(); i++)
              {
                  JSONObject c = (JSONObject)docs.getJSONObject(i);
                   
                  // Storing each json item in variable
                  String senderName = c.getString("sender");
                  String senderOrg = c.getString("org_name");
                  String requestItem = c.getString("itemname");
                  // creating new HashMap
                  HashMap<String, String> map = new HashMap<String, String>();
                  
                  map.put("sender", senderName);
                  map.put("org_name", senderOrg);
                  map.put("itemname",requestItem);
                   
                  // adding each child node to HashMap key => value
                 /* map.put("pid", pid);
                  map.put("zip", zip);
                  map.put("name", name);
                  map.put("ownername", ownername);
                  map.put("streetaddress", streetAddress);
                  map.put("city", city);
                  map.put("state",state);*/
   
                  // adding HashList to ArrayList
                  requestsList.add(map);
                  //Log.d("DisplayMatchingPlace", pid + " " + ownername + " " + name + " " + city + " " + state);
              }
      }
          catch (JSONException e)
          {
            e.printStackTrace();
          }
      
      /**
           * Updating parsed JSON data into ListView
           * */
      requests = new String[requestsList.size()];
      int i = 0;
      for (HashMap<String,String> map: requestsList)
      {
        String s = map.get("sender") + ", "+ (String)map.get("org_name")
              + "," + (String)map.get("itemname");
        requests[i++] = s;
      }
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.context,android.R.layout.simple_list_item_1 , requests);
      lv.setAdapter(adapter);
      lv.setClickable(true);
      lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          Log.d("DisplayRequestActivity", "Position = "+position);
          Intent displayRequest = new Intent(view.getContext(), DisplayRequestActivity.class);
          displayRequest.putExtra("request", requests[position]);
          context.startActivity(displayRequest);
        }
      });
     }

}




Java Source Code List

cs499.examples.semesterproject.AddItemsActivity.java
cs499.examples.semesterproject.AndroidFoodBankOwnerServlet.java
cs499.examples.semesterproject.AsyncAddItems.java
cs499.examples.semesterproject.AsyncAddPlace.java
cs499.examples.semesterproject.AsyncAddRestaurantToDB.java
cs499.examples.semesterproject.AsyncAuthenticateUser.java
cs499.examples.semesterproject.AsyncSearchAndShowPlaces.java
cs499.examples.semesterproject.AsyncSearchItems.java
cs499.examples.semesterproject.AsyncSendRequest.java
cs499.examples.semesterproject.AsyncViewRequests.java
cs499.examples.semesterproject.Constants.java
cs499.examples.semesterproject.DisplayMap.java
cs499.examples.semesterproject.DisplayMatchingPlaces.java
cs499.examples.semesterproject.DisplayPlaceItems.java
cs499.examples.semesterproject.DisplayPlace.java
cs499.examples.semesterproject.DisplayRequestActivity.java
cs499.examples.semesterproject.FoodBankOwnerActivity.java
cs499.examples.semesterproject.FoodOwnerOptions.java
cs499.examples.semesterproject.LoginActivity.java
cs499.examples.semesterproject.MainActivity.java
cs499.examples.semesterproject.OrganizationOptions.java
cs499.examples.semesterproject.OtherOwnerActivity.java
cs499.examples.semesterproject.QueryActivity.java
cs499.examples.semesterproject.ViewRequests.java
org.json.CDL.java
org.json.CookieList.java
org.json.Cookie.java
org.json.HTTPTokener.java
org.json.HTTP.java
org.json.JSONArray.java
org.json.JSONException.java
org.json.JSONML.java
org.json.JSONObject.java
org.json.JSONString.java
org.json.JSONStringer.java
org.json.JSONTokener.java
org.json.JSONWriter.java
org.json.Kim.java
org.json.Property.java
org.json.XMLTokener.java
org.json.XML.java
org.json.zip.BitInputStream.java
org.json.zip.BitOutputStream.java
org.json.zip.BitReader.java
org.json.zip.BitWriter.java
org.json.zip.Compressor.java
org.json.zip.Decompressor.java
org.json.zip.Huff.java
org.json.zip.JSONzip.java
org.json.zip.Keep.java
org.json.zip.MapKeep.java
org.json.zip.None.java
org.json.zip.PostMortem.java
org.json.zip.TrieKeep.java