Search in sources :

Example 1 with RequestMethod

use of com.se491.chef_ly.http.RequestMethod in project chefly_android by chef-ly.

the class MyService method onHandleIntent.

// called automaticly when server starts, receives data as an argument
@Override
protected void onHandleIntent(Intent intent) {
    RequestMethod requestPackage = intent.getParcelableExtra(REQUEST_PACKAGE);
    String sender = intent.getStringExtra("Tag");
    Log.d(TAG, "Sender -> " + sender);
    Log.d(TAG, "Request Package Endpoint-> " + requestPackage.getEndpoint());
    String response;
    try {
        HttpConnection http = new HttpConnection();
        response = http.downloadFromFeed(requestPackage);
    } catch (IOException e) {
        // e.printStackTrace();
        return;
    }
    Log.d(TAG, "Response -> " + response);
    GsonBuilder builder = new GsonBuilder();
    // builder.registerTypeAdapter(Uri.class, new JsonDeserializer<Uri>() {
    // @Override
    // public Uri deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    // return Uri.parse(json.toString());
    // }
    // });
    Gson gson = builder.create();
    RecipeList dataItems;
    Type type = new TypeToken<RecipeList>() {
    }.getType();
    dataItems = gson.fromJson(response, type);
    Intent messageIntent = new Intent(MY_SERVICE_MESSAGE);
    messageIntent.putExtra(MY_SERVICE_RESPONSE_STRING, response);
    // messageIntent.putExtra(MY_SERVICE_PAYLOAD, "Service all done!"); //pass data back, set key value and message
    if (dataItems != null) {
        // pass back the data
        messageIntent.putExtra(MY_SERVICE_PAYLOAD, dataItems);
    } else {
        // unidentified sender - send empty parcel back
        messageIntent.putExtra(MY_SERVICE_PAYLOAD, new Parcelable() {

            @Override
            public int describeContents() {
                return 0;
            }

            @Override
            public void writeToParcel(Parcel dest, int flags) {
            }
        });
    // pass back the data
    }
    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());
    manager.sendBroadcast(messageIntent);
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Parcel(android.os.Parcel) Gson(com.google.gson.Gson) Intent(android.content.Intent) Parcelable(android.os.Parcelable) IOException(java.io.IOException) LocalBroadcastManager(android.support.v4.content.LocalBroadcastManager) Type(java.lang.reflect.Type) RecipeList(com.se491.chef_ly.model.RecipeList)

Example 2 with RequestMethod

use of com.se491.chef_ly.http.RequestMethod in project chefly_android by chef-ly.

the class RecipeDetailActivity method onStart.

/*
    private void textViewClicked() {
        ViewSwitcher switcher = (ViewSwitcher) findViewById(R.id.my_switcher);
        View currentView = switcher.getCurrentView();
        //switcher.showNext(); //or switcher.showPrevious();
        TextView viewText = (TextView) switcher.findViewById(R.id.directionView);
        EditText editText = (EditText) findViewById(R.id.hidden_edit_view);

        if (currentView instanceof EditText) {
            //Save steps and prepare next view (Text view)
            directionsForCooking = editText.getText().toString().split("\n");
            StringBuilder sb = new StringBuilder();
            int count = 1;
            for (String s : directionsForCooking) {
                sb.append(count);
                sb.append(":  ");
                sb.append(s);
                sb.append("\n");

                directionsForCooking[count - 1] = s;
                count++;
            }
            steps = sb.toString();
            viewText.setText(steps);
        }
        else if (currentView instanceof TextView) {
            // Prepare next view (Edit view)
            String tmpSteps = implode("\n", directionsForCooking);
            editText.setText(tmpSteps);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }
        switcher.showNext();

    }

    private static String implode(String separator, String... data) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length - 1; i++) {
            //data.length - 1 => to not add separator at the end
            if (!data[i].matches(" *")) {//empty string are ""; " "; "  "; and so on
                sb.append(data[i]);
                sb.append(separator);
            }
        }
        sb.append(data[data.length - 1].trim());
        return sb.toString();
    }
*/
@Override
protected void onStart() {
    super.onStart();
    Intent intent = getIntent();
    final String recipeID = intent.getStringExtra("recipe");
    RecipeInformation result = intent.getParcelableExtra("recipeDetail");
    if (result != null) {
        recipeDetail = result;
        setRecipeInfo();
    } else if (// returns true if internet available
    NetworkHelper.hasNetworkAccess(RecipeDetailActivity.this)) {
        // register to listen the data
        RequestMethod requestPackage = new RequestMethod();
        requestPackage.setEndPoint(urlString + recipeID);
        // or requestPackage.setMethod("POST");
        requestPackage.setMethod("GET");
        new AsyncTask<RequestMethod, Integer, Long>() {

            String resp = "";

            @Override
            protected Long doInBackground(RequestMethod... params) {
                for (RequestMethod r : params) {
                    try {
                        HttpConnection http = new HttpConnection();
                        resp = http.downloadFromFeed(r);
                        GsonBuilder builder = new GsonBuilder();
                        Gson gson = builder.create();
                        Type type;
                        type = new TypeToken<RecipeInformation>() {
                        }.getType();
                        recipeDetail = gson.fromJson(resp, type);
                        Log.d(TAG, recipeDetail.toString());
                    } catch (Exception e) {
                        // e.printStackTrace();
                        return -1L;
                    }
                    Log.d(TAG, resp);
                }
                return 1L;
            }

            @Override
            protected void onPostExecute(Long aLong) {
                super.onPostExecute(aLong);
                setRecipeInfo();
            }
        }.execute(requestPackage);
    } else {
        // Toast.makeText(RecipeListActivity.this,"No Internet Connection",Toast.LENGTH_LONG).show();
        Log.d(TAG, "No Internet Connection");
    }
}
Also used : Type(java.lang.reflect.Type) HttpConnection(com.se491.chef_ly.http.HttpConnection) GsonBuilder(com.google.gson.GsonBuilder) RequestMethod(com.se491.chef_ly.http.RequestMethod) TypeToken(com.google.gson.reflect.TypeToken) AsyncTask(android.os.AsyncTask) Gson(com.google.gson.Gson) Intent(android.content.Intent) RecipeInformation(com.se491.chef_ly.model.RecipeInformation) IOException(java.io.IOException)

Example 3 with RequestMethod

use of com.se491.chef_ly.http.RequestMethod in project chefly_android by chef-ly.

the class RecipeDetailActivity method setRecipeInfo.

private void setRecipeInfo() {
    final Context c = getApplicationContext();
    TextView author = (TextView) findViewById(R.id.recipeAuthor);
    // TextView description = (TextView) findViewById(R.id.recipeDescription);
    TextView serves = (TextView) findViewById(R.id.recipeServings);
    TextView time = (TextView) findViewById(R.id.recipeTime);
    String recipeName;
    Step[] directions;
    if (recipeDetail == null) {
        recipeTitle.setText(R.string.recipeNotFound);
    } else {
        recipeName = recipeDetail.getTitle();
        recipeTitle.setText(recipeName);
        author.setText(recipeDetail.getCreditText());
        int servings = recipeDetail.getServings();
        Log.d(TAG, "Serves -> " + servings);
        if (servings <= 0) {
            serves.setText(R.string.unknown);
        } else {
            serves.setText(String.valueOf(servings));
        }
        int cookTime = recipeDetail.getReadyInMinutes();
        int hour = 0;
        while (cookTime >= 60) {
            hour++;
            cookTime = cookTime - 60;
        }
        String newTime;
        if (hour < 2) {
            newTime = (hour != 0) ? hour + " hr " : "";
        } else {
            newTime = (hour != 0) ? hour + " hrs " : "";
        }
        newTime += ((cookTime > 0) ? cookTime + " min" : "");
        if (newTime.isEmpty()) {
            time.setText(R.string.unknown);
        } else {
            time.setText(newTime);
        }
        new AsyncTask<RequestMethod, Integer, Long>() {

            Bitmap image = null;

            @Override
            protected Long doInBackground(RequestMethod... params) {
                try {
                    URL url = new URL(recipeDetail.getImage());
                    image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                } catch (IOException e) {
                    Log.d(TAG, "IOException on load image");
                    Log.d(TAG, e.getMessage());
                }
                return 1L;
            }

            @Override
            protected void onPostExecute(Long aLong) {
                if (image != null) {
                    imageView.setImageBitmap(image);
                }
            }
        }.execute();
        ingredients = recipeDetail.getExtendedIngredients();
        if (recipeDetail.getAnalyzedInstructions().length > 0) {
            directions = recipeDetail.getAnalyzedInstructions()[0].getSteps();
        } else {
            directions = new Step[] { new Step(recipeDetail.getInstructions()) };
        }
        // checkBoxes = new CheckBox[ingredients.length];
        // int states[][] = {{android.R.attr.state_checked}, {}};
        TableLayout table = (TableLayout) findViewById(R.id.ingredientGroup);
        TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
        int leftMargin = 30;
        int topMargin = 1;
        int rightMargin = 30;
        int bottomMargin = 1;
        tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
        int color1 = getColor(c, R.color.table_color1);
        int color2 = getColor(c, R.color.table_color2);
        int count = 0;
        for (ExtendedIngredient s : ingredients) {
            final TableRow row = new TableRow(c);
            row.setLayoutParams(tableRowParams);
            row.setBackgroundColor(count % 2 == 0 ? color1 : color2);
            row.setPadding(10, 5, 10, 5);
            TextView text = new TextView(c);
            text.setText(s.getOriginalString());
            text.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
            text.setTextSize((getResources().getDimension(R.dimen.text_small) / getResources().getDisplayMetrics().density));
            text.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
            text.setPadding(10, 5, 10, 5);
            text.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    ImageView image = (ImageView) row.getChildAt(1);
                    String text = String.valueOf(((TextView) row.getChildAt(0)).getText());
                    if (row.getChildAt(1).getVisibility() == View.GONE) {
                        image.setVisibility(View.VISIBLE);
                        shoppingList.add(new ShoppingListItem(text, false));
                        Toast.makeText(c, text + " added to shopping list", Toast.LENGTH_SHORT).show();
                    } else {
                        image.setVisibility(View.GONE);
                        shoppingList.remove(new ShoppingListItem(text, false));
                        Toast.makeText(c, text + " removed from shopping list", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            row.addView(text);
            ImageView check = new ImageView(c);
            check.setImageResource(R.drawable.shoppinglist);
            check.setLayoutParams(new TableRow.LayoutParams(60, 60, 0.1f));
            if (shoppingList.contains(new ShoppingListItem(s.getOriginalString(), false))) {
                check.setVisibility(View.VISIBLE);
            } else {
                check.setVisibility(View.GONE);
            }
            row.addView(check);
            table.addView(row);
            count++;
        }
        // 
        final TableLayout tableDirec = (TableLayout) findViewById(R.id.directionGroup);
        tableDirec.setColumnShrinkable(0, true);
        tableDirec.setVisibility(View.GONE);
        directionsForCooking = new String[directions.length];
        count = 1;
        for (Step s : directions) {
            String step = count + ")  " + s.getStep();
            TableRow row = new TableRow(c);
            row.setLayoutParams(tableRowParams);
            row.setBackgroundColor(count % 2 == 0 ? color1 : color2);
            TextView text = new TextView(c);
            text.setText(step);
            text.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
            text.setTextSize((getResources().getDimension(R.dimen.text_small) / getResources().getDisplayMetrics().density));
            text.setPadding(15, 1, 15, 1);
            text.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
            row.addView(text);
            tableDirec.addView(row);
            directionsForCooking[count - 1] = s.getStep();
            count++;
        }
        final ScrollView sv = (ScrollView) findViewById(R.id.scrollView);
        final ImageButton dropdown = (ImageButton) findViewById(R.id.directionsDropdown);
        final RotateAnimation rotatedown = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotatedown.setDuration(250);
        rotatedown.setFillAfter(true);
        final RotateAnimation rotateup = new RotateAnimation(180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateup.setDuration(250);
        rotateup.setFillAfter(true);
        dropdown.setOnClickListener(new View.OnClickListener() {

            private boolean isClicked = false;

            @Override
            public void onClick(View v) {
                if (!isClicked) {
                    tableDirec.setVisibility(View.VISIBLE);
                    dropdown.startAnimation(rotatedown);
                    isClicked = true;
                    sv.post(new Runnable() {

                        @Override
                        public void run() {
                            // sv.fullScroll(ScrollView.FOCUS_DOWN);
                            sv.smoothScrollBy(0, 500);
                        }
                    });
                } else {
                    dropdown.startAnimation(rotateup);
                    tableDirec.setVisibility(View.GONE);
                    isClicked = false;
                // sv.fullScroll(ScrollView.FOCUS_DOWN);
                }
            }
        });
    }
}
Also used : RequestMethod(com.se491.chef_ly.http.RequestMethod) Step(com.se491.chef_ly.model.Step) ExtendedIngredient(com.se491.chef_ly.model.ExtendedIngredient) URL(java.net.URL) RotateAnimation(android.view.animation.RotateAnimation) Bitmap(android.graphics.Bitmap) ImageButton(android.widget.ImageButton) TextView(android.widget.TextView) ImageView(android.widget.ImageView) TableLayout(android.widget.TableLayout) Context(android.content.Context) IOException(java.io.IOException) ShoppingListItem(com.se491.chef_ly.model.ShoppingListItem) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) ScrollView(android.widget.ScrollView) ScrollView(android.widget.ScrollView) TableRow(android.widget.TableRow)

Example 4 with RequestMethod

use of com.se491.chef_ly.http.RequestMethod in project chefly_android by chef-ly.

the class RecipeListActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recipe_list);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    // Progress bar for loading search
    spinner = (ProgressBar) findViewById(R.id.progressBar1);
    spinner.setVisibility(View.GONE);
    spinner.setIndeterminateDrawable(ContextCompat.getDrawable(this, R.drawable.customprogressbar));
    // Initialize recipe lists
    serverRecipes = new RecipeList();
    favoriteRecipes = new RecipeList();
    // Start AsyncTaskLoader to get FavoriteRecipes
    Credentials cred = CredentialsManager.getCredentials(getApplicationContext());
    String t = cred.getAccessToken();
    Log.d(TAG, "Token -> " + t);
    if (t != null) {
        RequestMethod requestPackageFavs = new RequestMethod();
        requestPackageFavs.setEndPoint(urlFavsString);
        requestPackageFavs.setMethod("GET");
        requestPackageFavs.setHeader("Authorization", "Bearer " + t);
        Bundle bundlefavs = new Bundle();
        bundlefavs.putParcelable("requestPackage", requestPackageFavs);
        getSupportLoaderManager().initLoader(FAVORTIESID, bundlefavs, this).forceLoad();
    } else {
        Toast.makeText(this, "Could not retrieve favorites, token is null", Toast.LENGTH_SHORT).show();
    }
    // PageViewer
    pager = (ViewPager) findViewById(R.id.viewpager);
    Bundle serv = new Bundle();
    serv.putString("title", "Recipes");
    serv.putString("pageNum", "1");
    serv.putString("search", "");
    server = new ListViewFragment();
    server.setArguments(serv);
    Bundle f = new Bundle();
    f.putString("title", "Favorites");
    f.putString("pageNum", "2");
    f.putString("search", "");
    favs = new ListViewFragment();
    favs.setArguments(f);
    ListViewFragment[] frags = { server, favs };
    pager.setAdapter(new RecipeListPagerAdapter(getSupportFragmentManager(), frags));
    pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // Log.d(TAG, "Position -> " + position);
            if (position == 1) {
                favoritesHeader.setPaintFlags(favoritesHeader.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
                recipesHeader.setPaintFlags(0);
            // ingredientsHeader.setPaintFlags(0);
            } else {
                recipesHeader.setPaintFlags(recipesHeader.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
                favoritesHeader.setPaintFlags(0);
            // ingredientsHeader.setPaintFlags(0);
            }
        }

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    // Header links
    // ingredientsHeader = (TextView) findViewById(R.id.ingredientsHeader);
    favoritesHeader = (TextView) findViewById(R.id.favortiesHeader);
    recipesHeader = (TextView) findViewById(R.id.recipesHeader);
    View.OnClickListener headerListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == favoritesHeader.getId()) {
                favoritesHeader.setPaintFlags(favoritesHeader.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
                recipesHeader.setPaintFlags(0);
                // ingredientsHeader.setPaintFlags(0);
                pager.setCurrentItem(1);
            } else {
                recipesHeader.setPaintFlags(recipesHeader.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
                favoritesHeader.setPaintFlags(0);
                // ingredientsHeader.setPaintFlags(0);
                pager.setCurrentItem(0);
            }
        }
    };
    // ingredientsHeader.setOnClickListener(headerListener);
    favoritesHeader.setOnClickListener(headerListener);
    recipesHeader.setOnClickListener(headerListener);
    // Tool/Appbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Navigation Drawer
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}
Also used : NavigationView(android.support.design.widget.NavigationView) RequestMethod(com.se491.chef_ly.http.RequestMethod) Bundle(android.os.Bundle) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) ViewPager(android.support.v4.view.ViewPager) NavigationView(android.support.design.widget.NavigationView) SearchView(android.support.v7.widget.SearchView) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) Paint(android.graphics.Paint) RecipeList(com.se491.chef_ly.model.RecipeList) DrawerLayout(android.support.v4.widget.DrawerLayout) Credentials(com.auth0.android.result.Credentials) Toolbar(android.support.v7.widget.Toolbar)

Example 5 with RequestMethod

use of com.se491.chef_ly.http.RequestMethod in project chefly_android by chef-ly.

the class RecipeListActivity method handleIntent.

// search by title
private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        queryString = intent.getStringExtra(SearchManager.QUERY);
        Toast.makeText(this, queryString, Toast.LENGTH_SHORT).show();
        // Put Search Logic Here
        RequestMethod requestPackage = new RequestMethod();
        // find the url
        requestPackage.setEndPoint(urlStringSearch + queryString + urlPageNum + 0);
        // send the post method request
        requestPackage.setMethod("GET");
        Bundle searchRecipes = new Bundle();
        searchRecipes.putParcelable("requestPackage", requestPackage);
        searchRecipes.putString("test", "Handle Intent");
        server.updateSearch(queryString);
        // getSupportLoaderManager().initLoader(SEARCHID, searchRecipes,this).forceLoad();
        getSupportLoaderManager().initLoader(queryString.hashCode(), searchRecipes, this).forceLoad();
    } else {
        Log.d(TAG, "Intent does not equal action search");
    }
}
Also used : RequestMethod(com.se491.chef_ly.http.RequestMethod) Bundle(android.os.Bundle)

Aggregations

RequestMethod (com.se491.chef_ly.http.RequestMethod)13 Bundle (android.os.Bundle)6 Intent (android.content.Intent)4 IOException (java.io.IOException)4 View (android.view.View)3 ImageView (android.widget.ImageView)3 TextView (android.widget.TextView)3 Gson (com.google.gson.Gson)3 GsonBuilder (com.google.gson.GsonBuilder)3 Type (java.lang.reflect.Type)3 Handler (android.os.Handler)2 TypeToken (com.google.gson.reflect.TypeToken)2 HttpConnection (com.se491.chef_ly.http.HttpConnection)2 RecipeInformation (com.se491.chef_ly.model.RecipeInformation)2 RecipeList (com.se491.chef_ly.model.RecipeList)2 Context (android.content.Context)1 Bitmap (android.graphics.Bitmap)1 Paint (android.graphics.Paint)1 AsyncTask (android.os.AsyncTask)1 Parcel (android.os.Parcel)1