Android Open Source - MobilHackathon2014 Results Activity






From Project

Back to project page MobilHackathon2014.

License

The source code is released under:

GNU General Public License

If you think the Android project MobilHackathon2014 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 com.github.barcodeeye.scan;
// ww  w  .  ja  va  2 s . c om
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.github.barcodeeye.R;
import com.google.android.glass.app.Card;
import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;

import com.google.android.glass.eye.EyeEventReceiver;
import com.google.android.glass.eye.EyeGesture;
import com.google.android.glass.eye.EyeGestureManager;
import com.google.android.glass.eye.EyeGestureManager.Listener;


public class ResultsActivity extends Activity {

    private static final String TAG = ResultsActivity.class.getSimpleName();
    private List<Card> mCards;
    private Context mContext;
  private CardScrollView mCardScrollView;
  private GestureDetector mGestureDetector;
  private boolean canClose;
  private boolean isLeftLayout;
  private int imageId;
  private String text;
  private String footnote;
  private String url;
  private String product;
  private String token;
  private int id;
  private int price;
  private int stock;
  private int remaining;
  private int remainingTime = 10;
  
  private EyeGestureManager mEyeGestureManager;
  private EyeEventReceiver mEyeEventReceiver;
  private EyeGestureListener mEyeGestureListener;
    
  //runs without a timer by reposting this handler at the end of the runnable
  Handler timerHandler = new Handler();
  Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {
      remainingTime--;
      Log.d(TAG, "Remaining time " + remainingTime);
      updateCards();
      
      if(remainingTime != 0)
        timerHandler.postDelayed(this, 1000);
      else{
            closeMe();
      }
    }
  };
    
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    id = 0;
    canClose = false;
    mContext = this;
    mGestureDetector = createGestureDetector(this);
    url = getIntent().getExtras().getString("url");
    createCards("Veriler ?ekiliyor...","L?tfen Bekleyin...",R.drawable.refresh);
    
    mEyeGestureManager = EyeGestureManager.from(this);
        for (EyeGesture eg : EyeGesture.values()) {
            boolean supported = mEyeGestureManager.isSupported(eg);
            Log.d("WinkDetector", eg.name() + ":" + supported);
        }
    
    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.pair_result_key), Context.MODE_PRIVATE);
    token = sharedPref.getString(getString(R.string.pair_result_key), "");
    new HttpAsyncTask().execute(url);
  }
  
  @Override
    protected void onStart() {
    Log.d(TAG, "----------ON START");
        super.onStart();
        setupReceiver();
    }


  @Override
  protected void onPause() {
    super.onPause();
    Log.d(TAG, "----------ON PAUSE");
    timerHandler.removeCallbacks(timerRunnable);
    
        removeReceiver();
  }

  @Override
  protected void onResume() {
    Log.d(TAG, "----------ON RESUME");
    super.onResume();
  }
  
  private void closeMe(){
    Intent intent = new Intent(mContext, CaptureActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
    finish();
  }
  
    public void removeReceiver() {
        //mEyeGestureManager.unregister(EyeGesture.BLINK, mEyeGestureListener);
        mEyeGestureManager.unregister(EyeGesture.DOUBLE_BLINK, mEyeGestureListener);
        mEyeGestureManager.unregister(EyeGesture.WINK, mEyeGestureListener);
        //mEyeGestureManager.unregister(EyeGesture.DOUBLE_WINK, mEyeGestureListener);
        //mEyeGestureManager.unregister(EyeGesture.DOFF, mEyeGestureListener);
        try {
            getApplicationContext().unregisterReceiver(mEyeEventReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setupReceiver() {
        mEyeGestureManager = EyeGestureManager.from(getApplicationContext());
        mEyeGestureListener = new EyeGestureListener();

        //mEyeGestureManager.register(EyeGesture.BLINK, mEyeGestureListener);
        mEyeGestureManager.register(EyeGesture.DOUBLE_BLINK, mEyeGestureListener);
        mEyeGestureManager.register(EyeGesture.WINK, mEyeGestureListener);
        //mEyeGestureManager.register(EyeGesture.DOUBLE_WINK, mEyeGestureListener);
        //mEyeGestureManager.register(EyeGesture.DOFF, mEyeGestureListener);
    }
    
    private class EyeGestureListener implements Listener {
        @Override
        public void onEnableStateChange(EyeGesture eyeGesture, boolean paramBoolean) {
            Log.i(TAG, eyeGesture + " state changed:" + paramBoolean);
        }

        @Override
        public void onDetected(final EyeGesture eyeGesture) {
          Log.i(TAG, "eyeGesture detected:" + eyeGesture.name());
          
          if(eyeGesture == EyeGesture.WINK){
                if(id != 0){
                  timerHandler.removeCallbacks(timerRunnable);
                  createCards("??leminiz yap?l?yor...","L?tfen Bekleyin...",R.drawable.refresh);
                    String addToChartUrl = "http://54.72.214.188:3101/glass/order/"+id+"?token=" + token;
                    id = 0;
                    remainingTime = 10;
              new HttpAsyncTask().execute(addToChartUrl);
                }
                else if(canClose){
                  closeMe();
                }
          }
        }
    }

  
  /*
   * Send generic motion events to the gesture detector
   */
  @Override
  public boolean onGenericMotionEvent(MotionEvent event) {
      if (mGestureDetector != null) {
          return mGestureDetector.onMotionEvent(event);
      }
      return false;
  }

  private GestureDetector createGestureDetector(Context context){
      GestureDetector gestureDetector = new GestureDetector(context);
      //Create a base listener for generic gestures
      gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
          @Override
          public boolean onGesture(Gesture gesture) {
              Log.d(TAG,"gesture = " + gesture);
              switch (gesture) {
                  case TAP:
                      Log.d(TAG,"TAP called.");
                      if(id != 0){
                        timerHandler.removeCallbacks(timerRunnable);
                        createCards("??leminiz yap?l?yor...","L?tfen Bekleyin...",R.drawable.refresh);
                          String addToChartUrl = "http://54.72.214.188:3101/glass/order/"+id+"?token=" + token;
                          id = 0;
                          remainingTime = 10;
                    new HttpAsyncTask().execute(addToChartUrl);
                      }
                      return true;
              }

              return false;
          }
      });
      return gestureDetector;
  }
  
  private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return GET(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
          Log.d(TAG, "result for http get" + result);
          try {  
        JSONObject jObject = new JSONObject(result);
        String type = jObject.getString("type");
        if(type.equals("auth")){
          token = jObject.getString("token");
          SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.pair_result_key), Context.MODE_PRIVATE);
          Editor editor = sharedPref.edit();
          editor.putString(getString(R.string.pair_result_key), token);
          editor.commit();
          canClose = true;
          createCards("Cihazlar?n?z? ba?ar?l? olarak e?le?tirdiniz.","??k?? i?in g?z k?rp?n, ya da bekleyin",R.drawable.success);
        }
        else if(type.equals("product")){
          if(token == ""){
            canClose = true;
            createCards("??lem ba?ar?s?z!\n?nce cihazlar?n?z? e?le?tirmelisiniz.","??k?? i?in g?z k?rp?n, ya da bekleyin",R.drawable.error);
          }
          else {
            product = jObject.getString("name");
            id = jObject.getInt("id");
            price = jObject.getInt("price");
            stock = jObject.getInt("stock");
            remaining = jObject.getInt("remaining");
            createCards(product + ", " + price + " TL\nStokta kalan: " + remaining + "/" + stock, "\nSepete eklemek i?in g?z k?rp?n. Kalan zaman",R.drawable.question);
          }
        }
        else if(type.equals("order")){
          if(token == ""){
            createCards("??lem ba?ar?s?z!\n?nce cihazlar?n?z? e?le?tirmelisiniz.","??k?? i?in g?z k?rp?n, ya da bekleyin",R.drawable.error);
          }
          else {
            boolean success = jObject.getBoolean("success");
            if(success)
              createLeftLayoutCards(product + " sepetinize eklendi.","??k?? i?in g?z k?rp?n",R.drawable.small_tick);
            else
              createLeftLayoutCards("??lem ba?ar?s?z!\n"+product+" sepetinize eklenemedi!","??k?? i?in g?z k?rp?n",R.drawable.small_cross);
          }
          canClose = true;
        }
        else if(type.equals("server_error")){
          createCards("Sunucuya eri?ilemiyor!\nL?tfen A? ayarlar?n?z? kontrol edin.","??k?? i?in g?z k?rp?n, ya da bekleyin",R.drawable.error);
          canClose = true;
        }
        else if(type.equals("server_bad_response")){
          createCards("404 sayfa bulunamad?!\nSunucu bu iste?e yan?t veremiyor.","??k?? i?in g?z k?rp?n, ya da bekleyin",R.drawable.error);
          canClose = true;
        }
        timerHandler.postDelayed(timerRunnable, 1000);
      } catch (JSONException e) {
        Log.d(TAG,"Add to chart is failed.");
        e.printStackTrace();
      }
       }
    }
  
  public static String GET(String url){
    Log.d(TAG, "http get for: " + url);
        InputStream inputStream = null;
        String result = "";
        try {
          
          HttpParams httpParameters = new BasicHttpParams();
          HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
          HttpConnectionParams.setSoTimeout(httpParameters, 2000);

          // create HttpClient
          HttpClient httpclient = new DefaultHttpClient(httpParameters);
          
          // create http get request
          HttpGet request = new HttpGet(url);

          // make GET request to the given URL
          HttpResponse httpResponse = httpclient.execute(request);
 
          // receive response as inputStream
          if(httpResponse.getStatusLine().getStatusCode() == 200)
            inputStream = httpResponse.getEntity().getContent();
 
            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "{\"type\":\"server_bad_response\"}";
 
        } catch (Exception e) {
            result = "{\"type\":\"server_error\"}";
        }
 
        return result;
    }
  
  private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;
 
        inputStream.close();
        return result;
 
    }

  private void createCards(boolean showRemainingTime, boolean _isLeftLayout, boolean isDeepCreate, String _text, String _footnote, int _imageId) {
    if(isDeepCreate){
      text = _text;
      footnote = _footnote;
      imageId = _imageId;
      isLeftLayout = _isLeftLayout;
    }
    mCards = new ArrayList<Card>();

    Card card;

    card = new Card(this);
    card.setText(_text);
    card.setFootnote(_footnote);
    if(showRemainingTime)
      card.setTimestamp(Integer.toString(remainingTime));
    
    if(_isLeftLayout)
      card.setImageLayout(Card.ImageLayout.LEFT);
    else
      card.setImageLayout(Card.ImageLayout.FULL);
    card.addImage(_imageId);
    mCards.add(card);
    
    mCardScrollView = new CardScrollView(this);
    ExampleCardScrollAdapter adapter = new ExampleCardScrollAdapter();
    mCardScrollView.setAdapter(adapter);
    mCardScrollView.activate();
    setContentView(mCardScrollView);
  }
  
  private void createLeftLayoutCards(String _text, String _footnote, int _imageId){
    createCards(false,true, true, _text, _footnote, _imageId);
  }
  
  private void createCards(String _text, String _footnote, int _imageId){
    createCards(false,false, true, _text, _footnote, _imageId);
  }
  
  private void updateCards() {
    createCards(true, isLeftLayout,false, text, footnote, imageId);
  }

    private class ExampleCardScrollAdapter extends CardScrollAdapter {

    @Override
    public int getPosition(Object item) {
      return mCards.indexOf(item);
    }

    @Override
    public int getCount() {
      return mCards.size();
    }

    @Override
    public Object getItem(int position) {
      return mCards.get(position);
    }

    @Override
    public int getViewTypeCount() {
      return Card.getViewTypeCount();
    }

    @Override
    public int getItemViewType(int position){
      return mCards.get(position).getItemViewType();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      return  mCards.get(position).getView(convertView, parent);
    }
    }
}




Java Source Code List

com.github.barcodeeye.BaseGlassActivity.java
com.github.barcodeeye.LaunchActivity.java
com.github.barcodeeye.image.ImageManager.java
com.github.barcodeeye.migrated.AmbientLightManager.java
com.github.barcodeeye.migrated.BeepManager.java
com.github.barcodeeye.migrated.DecodeFormatManager.java
com.github.barcodeeye.migrated.DecodeHintManager.java
com.github.barcodeeye.migrated.FinishListener.java
com.github.barcodeeye.migrated.HttpHelper.java
com.github.barcodeeye.migrated.InactivityTimer.java
com.github.barcodeeye.migrated.Intents.java
com.github.barcodeeye.migrated.LocaleManager.java
com.github.barcodeeye.scan.CaptureActivityHandler.java
com.github.barcodeeye.scan.CaptureActivity.java
com.github.barcodeeye.scan.DecodeHandler.java
com.github.barcodeeye.scan.DecodeThread.java
com.github.barcodeeye.scan.ResultsActivity.java
com.github.barcodeeye.scan.api.CardPresenter.java
com.github.barcodeeye.scan.ui.ViewfinderView.java
com.google.android.glass.eye.EyeEventReceiver.java
com.google.android.glass.eye.EyeGestureManager.java
com.google.android.glass.eye.EyeGesture.java
com.google.zxing.client.android.camera.AutoFocusManager.java
com.google.zxing.client.android.camera.CameraConfigurationManager.java
com.google.zxing.client.android.camera.CameraManager.java
com.google.zxing.client.android.camera.PreviewCallback.java
com.google.zxing.client.android.camera.open.OpenCameraInterface.java
com.google.zxing.client.android.clipboard.ClipboardInterface.java
com.google.zxing.client.android.encode.ContactEncoder.java
com.google.zxing.client.android.encode.Formatter.java
com.google.zxing.client.android.encode.MECARDContactEncoder.java
com.google.zxing.client.android.encode.VCardContactEncoder.java
com.google.zxing.client.android.history.DBHelper.java
com.google.zxing.client.android.history.HistoryItemAdapter.java
com.google.zxing.client.android.history.HistoryItem.java
com.google.zxing.client.android.share.AppInfo.java
com.google.zxing.client.android.share.AppPickerActivity.java
com.google.zxing.client.android.share.BookmarkAdapter.java
com.google.zxing.client.android.share.BookmarkPickerActivity.java
com.google.zxing.client.android.share.LoadPackagesAsyncTask.java
com.google.zxing.client.android.wifi.NetworkType.java
com.google.zxing.client.android.wifi.WifiConfigManager.java
edu.hackathon.perseus.app.AboutActivity.java
edu.hackathon.perseus.app.MainActivity.java
edu.hackathon.perseus.app.MainService.java
edu.hackathon.perseus.core.appLogger.java
edu.hackathon.perseus.core.httpSpeedTest.java