Gif или спрайт для анимации на Android

Встал вопрос о том, как лучше сделать анимацию на Android. Gif или спрайтом, какие плюсы и минусы обоих подходов. Возможно есть другие варианты.

Мы хотим сделать анимацию flat-персонажа.
Похожую на эту работу

Спасибо.

All topic

What are some fast ways to install same apks on 400 android tablet?

I work at a school who wants to implement a modern education system with tablets.
There will be around 400 tablet all should have a few applications installed for students to use.

I’m planning to have the apps as apk and install them but this will definitely take a lot of time. Is there any way you would advise me to? Can I upload them online and have the tablets in some kind of way to automatically install them online?

I really appreciate your help.

All topic

Не скрывается фрагмент в Android

В общем, сам фрагмент создается на экране без проблем, но не скрывается, ниже привожу код. Идея какая, чтобы при нечетном нажатии на картинку фрагмент появлялся, а при четном скрывался

                val fragment = PrinterFragment()

                // Get the support fragment manager instance
                val manager = supportFragmentManager

                // Begin the fragment transition using support fragment manager
                val transaction = manager.beginTransaction()



            if(menuFlag == false) {
                // Replace the fragment on container

                transaction.replace(R.id.fragment_container, fragment)
                transaction.addToBackStack(null)
                menuFlag = true


            }else if(menuFlag == true){

                transaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out)
                transaction.hide(fragment)
                menuFlag = false
            }



                // Finishing the transition
                transaction.commit()

All topic

OpenALをAndroid studioでも適用する方法

OpenALというものに最近触れまして、visual studioのc言語で色々試していました。

そこで色々調べていくと、最近勉強したいと考えているAndroidでもopenALライブラリが使えると聞いて早速導入しようとしてみました。

しかし、導入方法にEclipseで実行するという方法しか見つからず、android studioで動かし方がわかりません。

http://akihiro-i.net/~akihiro-i/wiki/index.php?Android%A4%C7OpenAL%A4%F2%BB%C8%A4%C3%A4%C6%A5%AA%A1%BC%A5%C7%A5%A3%A5%AA%A5%A2%A5%D7%A5%EA%A4%F2%BA%EE%C0%AE%A4%B9%A4%EB

上記のサイトを試して、
android-ndkでコンパイル、.soファイルの作成まではいきましたが、android studioの場合どうすればいいのでしょうか?

All topic

Restore an Android device stuck in download mode from ADB backup

The device is a Samsung Tab 3 7.0 and due to a series of mistakes on trying to root it, it won’t boot up anymore. It doesn’t go into restore mode (power+vol up+home) for some reason but it does go into download mode.

Is there a way to restore it?

All topic

Android Development Java this Keword

i want to understand how “this” keyward work in this code cause iam confused how implementation of “ListItemClickListener” been pathed by calling “this” since “ListItemClickListener” is interface



public class MainActivity extends AppCompatActivity implements GreenAdapter.ListItemClickListener{

private static final int NUM_LIST_ITEMS = 100;

/*
 * References to RecyclerView and Adapter to reset the list to its
 * "pretty" state when the reset menu item is clicked.
 */
private GreenAdapter mAdapter;
private RecyclerView mNumbersList;

// TODO (9) Create a Toast variable called mToast to store the current Toast

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    /*
     * Using findViewById, we get a reference to our RecyclerView from xml. This allows us to
     * do things like set the adapter of the RecyclerView and toggle the visibility.
     */
    mNumbersList = (RecyclerView) findViewById(R.id.rv_numbers);

    /*
     * A LinearLayoutManager is responsible for measuring and positioning item views within a
     * RecyclerView into a linear list. This means that it can produce either a horizontal or
     * vertical list depending on which parameter you pass in to the LinearLayoutManager
     * constructor. By default, if you don't specify an orientation, you get a vertical list.
     * In our case, we want a vertical list, so we don't need to pass in an orientation flag to
     * the LinearLayoutManager constructor.
     *
     * There are other LayoutManagers available to display your data in uniform grids,
     * staggered grids, and more! See the developer documentation for more details.
     */
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    mNumbersList.setLayoutManager(layoutManager);

    /*
     * Use this setting to improve performance if you know that changes in content do not
     * change the child layout size in the RecyclerView
     */
    mNumbersList.setHasFixedSize(true);

    // TODO (13) Pass in this as the ListItemClickListener to the GreenAdapter constructor
    /*
     * The GreenAdapter is responsible for displaying each item in the list.
     */
    mAdapter = new GreenAdapter(NUM_LIST_ITEMS,this);
    mNumbersList.setAdapter(mAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int itemId = item.getItemId();

    switch (itemId) {
        /*
         * When you click the reset menu item, we want to start all over
         * and display the pretty gradient again. There are a few similar
         * ways of doing this, with this one being the simplest of those
         * ways. (in our humble opinion)
         */
        case R.id.action_refresh:
            // TODO (14) Pass in this as the ListItemClickListener to the GreenAdapter constructor
            mAdapter = new GreenAdapter(NUM_LIST_ITEMS,this);
            mNumbersList.setAdapter(mAdapter);
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onListitemClick(int parameter) {

    Toast.makeText(this,"sasa"+Integer.toString(parameter),Toast.LENGTH_LONG).show();

}

}


public class GreenAdapter extends RecyclerView.Adapter {

private static final String TAG = GreenAdapter.class.getSimpleName();
final private ListItemClickListener mOnClickListener;

// TODO (3) Create a final private ListItemClickListener called mOnClickListener

/*
 * The number of ViewHolders that have been created. Typically, you can figure out how many
 * there should be by determining how many list items fit on your screen at once and add 2 to 4
 * to that number. That isn't the exact formula, but will give you an idea of how many
 * ViewHolders have been created to display any given RecyclerView.
 *
 * Here's some ASCII art to hopefully help you understand:
 *
 *    ViewHolders on screen:
 *
 *        *-----------------------------*
 *        |         ViewHolder index: 0 |
 *        *-----------------------------*
 *        |         ViewHolder index: 1 |
 *        *-----------------------------*
 *        |         ViewHolder index: 2 |
 *        *-----------------------------*
 *        |         ViewHolder index: 3 |
 *        *-----------------------------*
 *        |         ViewHolder index: 4 |
 *        *-----------------------------*
 *        |         ViewHolder index: 5 |
 *        *-----------------------------*
 *        |         ViewHolder index: 6 |
 *        *-----------------------------*
 *        |         ViewHolder index: 7 |
 *        *-----------------------------*
 *
 *    Extra ViewHolders (off screen)
 *
 *        *-----------------------------*
 *        |         ViewHolder index: 8 |
 *        *-----------------------------*
 *        |         ViewHolder index: 9 |
 *        *-----------------------------*
 *        |         ViewHolder index: 10|
 *        *-----------------------------*
 *        |         ViewHolder index: 11|
 *        *-----------------------------*
 *
 *    Total number of ViewHolders = 11
 */
private static int viewHolderCount;

private int mNumberItems;

interface ListItemClickListener{

    void onListitemClick(int parameter);


}

// TODO (1) Add an interface called ListItemClickListener
// TODO (2) Within that interface, define a void method called onListItemClick that takes an int as a parameter

// TODO (4) Add a ListItemClickListener as a parameter to the constructor and store it in mOnClickListener
/**
 * Constructor for GreenAdapter that accepts a number of items to display and the specification
 * for the ListItemClickListener.
 *
 * @param numberOfItems Number of items to display in list
 */
public GreenAdapter(int numberOfItems,ListItemClickListener listItemClickListener) {
    mOnClickListener=listItemClickListener;
    mNumberItems = numberOfItems;
    viewHolderCount = 0;
}

/**
 *
 * This gets called when each new ViewHolder is created. This happens when the RecyclerView
 * is laid out. Enough ViewHolders will be created to fill the screen and allow for scrolling.
 *
 * @param viewGroup The ViewGroup that these ViewHolders are contained within.
 * @param viewType  If your RecyclerView has more than one type of item (which ours doesn't) you
 *                  can use this viewType integer to provide a different layout. See
 *                  {@link android.support.v7.widget.RecyclerView.Adapter#getItemViewType(int)}
 *                  for more details.
 * @return A new NumberViewHolder that holds the View for each list item
 */
@Override
public NumberViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    Context context = viewGroup.getContext();
    int layoutIdForListItem = R.layout.number_list_item;
    LayoutInflater inflater = LayoutInflater.from(context);
    boolean shouldAttachToParentImmediately = false;

    View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
    NumberViewHolder viewHolder = new NumberViewHolder(view);

    viewHolder.viewHolderIndex.setText("ViewHolder index: " + viewHolderCount);

    int backgroundColorForViewHolder = ColorUtils
            .getViewHolderBackgroundColorFromInstance(context, viewHolderCount);
    viewHolder.itemView.setBackgroundColor(backgroundColorForViewHolder);

    viewHolderCount++;
    Log.d(TAG, "onCreateViewHolder: number of ViewHolders created: "
            + viewHolderCount);
    return viewHolder;
}

/**
 * OnBindViewHolder is called by the RecyclerView to display the data at the specified
 * position. In this method, we update the contents of the ViewHolder to display the correct
 * indices in the list for this particular position, using the "position" argument that is conveniently
 * passed into us.
 *
 * @param holder   The ViewHolder which should be updated to represent the contents of the
 *                 item at the given position in the data set.
 * @param position The position of the item within the adapter's data set.
 */
@Override
public void onBindViewHolder(NumberViewHolder holder, int position) {
    Log.d(TAG, "#" + position);
    holder.bind(position);
}

/**
 * This method simply returns the number of items to display. It is used behind the scenes
 * to help layout our Views and for animations.
 *
 * @return The number of items available
 */
@Override
public int getItemCount() {
    return mNumberItems;
}

// TODO (5) Implement OnClickListener in the NumberViewHolder class
/**
 * Cache of the children views for a list item.
 */
class NumberViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {



    // Will display the position in the list, ie 0 through getItemCount() - 1
    TextView listItemNumberView;
    // Will display which ViewHolder is displaying this data
    TextView viewHolderIndex;

    /**
     * Constructor for our ViewHolder. Within this constructor, we get a reference to our
     * TextViews and set an onClickListener to listen for clicks. Those will be handled in the
     * onClick method below.
     * @param itemView The View that you inflated in
     *                 {@link GreenAdapter#onCreateViewHolder(ViewGroup, int)}
     */
    public NumberViewHolder(View itemView) {
        super(itemView);

itemView.setOnClickListener(this);
listItemNumberView = (TextView) itemView.findViewById(R.id.tv_item_number);
viewHolderIndex = (TextView) itemView.findViewById(R.id.tv_view_holder_instance);
// TODO (7) Call setOnClickListener on the View passed into the constructor (use ‘this’ as the OnClickListener)
}

    /**
     * A method we wrote for convenience. This method will take an integer as input and
     * use that integer to display the appropriate text within a list item.
     * @param listIndex Position of the item in the list
     */
    void bind(int listIndex) {
        listItemNumberView.setText(String.valueOf(listIndex));
    }

    @Override
    public void onClick(View view) {
        int clickPostion=getAdapterPosition();
        mOnClickListener.onListitemClick(clickPostion);
    }

    // TODO (6) Override onClick, passing the clicked item's position (getAdapterPosition()) to mOnClickListener via its onListItemClick method
}

}

All topic

Внедрение в клиент-серверное android приложение архитектуры, базовые вопросы

Я на данный момент занимаюсь разработкой приложения под ОС Android. Это клиент-серверное приложение, которое посылает запросы и получает ответы с сервера, то есть у этого приложения довольно тесная связь с сервером.

Как все на данный момент работает: есть интерфейс в котором прописаны все запросы (POST,DELETE,PUT,GET). В каждом запросе используется специальный класс-модель описывающий все поля которые приходят в ответе сервера. Есть куча активити и фрагментов которые вызывают методы классов-моделей для заполнения экрана разнообразной информацией. У меня есть специальные функции для каждого вида запросов, например для обновления.

По факту сейчас приложение имеет определенный функционал, и вроде работает более-менее стабильно. Но, я недавно столкнулся с статьей, в которой написано что использование архитектуры в разработке под мобильные устройства имеет много преимуществ. Например, если я правильно понял, приложение получает подобие модульности, и все модули независимы между собой. Это означает что при внедрении каких-то значительных изменений не нужно перепиливать весь проект. Я не спорю что это довольно интересная особенность архитектуры.

Сейчас меня начнут заваливать воплями типа “почитай вот статью”, или “погугли прежде чем спрашивать такие тупые вопросы”. Дорогие господа и дамы, я много искал информации по этому вопросу. Вот например статья на хабре, или вот еще одна. Вроде все понятно написано, куча текста и картинок, но я если честно все-равно не понял. Возможно, у меня уже есть архитектура, я не знаю, но если ее нету, то хотелось бы услышать мнения по поводу ее внедрения. Просто сейчас есть функционал, и возможно архитектура, я не знаю.

Очень надеюсь на вашу помощь в этом вопросе. Желательно объяснить просто и на пальцах, потому что я серьезно начинаю задумываться над этим вопросом.

All topic

Yoga android app

This is my project I have created a yoga app on android studio can someone review through the code to see if I have used the best practices of programming.Thank you.

MainActivity:

package mo.youga;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;


public class MainActivity extends AppCompatActivity {


    //GOOGLE AD MOB
    private RewardedVideoAd RewardedVideoAd;
    //GOOGLE AD MOB

    Button Poses,Setting,Calendar;
    ImageView Training;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Poses=(Button)findViewById(R.id.Poses);
        Setting=(Button)findViewById(R.id.Setting);
        Training=(ImageView)findViewById(R.id.Training);
        Calendar=(Button)findViewById(R.id.Calendar);


        //listener for calendar
        Calendar.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent intent= new Intent(MainActivity.this,Calendar.class);
                startActivity(intent);
            }


        });



        //listener for training
        Training.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent intent= new Intent(MainActivity.this,DailyTraining.class);
                startActivity(intent);
            }


        });


        //listener for setting
        Setting.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            Intent intent= new Intent(MainActivity.this,Setting.class);
            startActivity(intent);
            }
        });


        //listener for poses
        Poses.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            Intent intent= new Intent(MainActivity.this,ListOfPoses.class);
            startActivity(intent);
            }
        });
/*
***********************************************************************************************************
* *********************************************************************************************************
* *********************************************************************************************************
* *********************************************************************************************************
 */
        //THIS IS GOOGLE AD MOBS FIX THIS

        //  AdMob app ID: ca-app-pub-4935262637979763~8258229167
        MobileAds.initialize(this, "ca-app-pub-4935262637979763~8258229167");

        // Use an activity context to get the rewarded video instance.
        RewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        RewardedVideoAd.setRewardedVideoAdListener((RewardedVideoAdListener) this);

        //LOAD REWARDED VIDEO AD
        loadRewardedVideoAd();



    }

    //GOOGLE ADS USE THIS
    //LOAD REWARDED VIDEO ADVERT AD MOB
    private void loadRewardedVideoAd() {
        RewardedVideoAd.loadAd("ca-app-pub-4935262637979763/2567026581",
                new AdRequest.Builder().build());
    }//END




}

Setting:

package mo.youga;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
//IMPORTING FROM OWN PACKAGE
import java.util.Calendar;
import java.util.Date;
import java.util.*;
import java.io.*;

import mo.youga.Database.YougaDB;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;



public class Setting extends AppCompatActivity {

    Button Save;
    RadioButton Easy, Intermediate, Difficult;
    RadioGroup Group;
    YougaDB yougaDB;
    ToggleButton switchAlarm;
    TimePicker timePicker;

    /*
   protected  T findViewById(@IdRes int id) {
        return (T) getRootView().findViewById(id);
    }

    this new class above will get the job done but it seems to cause error
    when i put it after the first protected class

     T findViewById()

    is the new way without causing
    any casting errors
     */

    /*
    alternatives to using above is using the common features of the View class they are:
    .setVisibility(View.VISIBLE);
    .onClick();
     */

    //on create
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_page);
        Save=(Button)findViewById(R.id.Save).setVisibility(View.VISIBLE);
        Group=(RadioGroup) findViewById(R.id.Group).setVisibility(View.VISIBLE);
        Easy=(RadioButton) findViewById(R.id.Easy).setVisibility(View.VISIBLE);
        Intermediate=(RadioButton) findViewById(R.id.Intermediate).setVisibility(View.VISIBLE);
        Difficult=(RadioButton) findViewById(R.id.Difficult).setVisibility(View.VISIBLE);
        switchAlarm=(ToggleButton) findViewById(R.id.switchAlarm).setVisibility(View.VISIBLE);
        timePicker=(TimePicker) findViewById(R.id.timePicker).setVisibility(View.VISIBLE);
        yougaDB=new YougaDB(this);

        //getting data from db and setting them
        int mode=yougaDB.getSettingMode();
        setRadioButton(mode);

        //event
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveWorkoutMode();
                saveAlarm(switchAlarm.isChecked());
                Toast.makeText(Setting.this, "Saved",Toast.LENGTH_SHORT).show();
                finish();
            }


        });


    }

    //save alarm
    //alarm
    private void saveAlarm(boolean checked) {
        if(checked){
            AlarmManager manager= (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent intent=new Intent(Setting.this,AlarmNotificationReceiver.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);

            //setting time
            Calendar calendar= Calendar.getInstance();
            Date Today= Calendar.getInstance().getTime();
            calendar.set(Today.getDay(), Today.getMonth(), Today.getYear(),timePicker.getCurrentHour(), timePicker.getCurrentMinute());

            manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

            //output messages for when the alarm will start safety measure
            Log.d("", "Alarm Starts In: "+timePicker.getCurrentHour()+":"+timePicker.getCurrentMinute());

            /*
            errors fixed via -> EFV
            errors caused -> EC

            EC: gethour and getminute
            EFV: getcurrenthour and getcurrentminute
            */
        }

        //cancelling alarm
        else{

            AlarmManager manager= (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent intent=new Intent(Setting.this,AlarmNotificationReceiver.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
            manager.cancel(pendingIntent);

        }

    }

    //save workout mode
    //data will be saved to database on save workout mode
    private void saveWorkoutMode(){
        int selectedID=Group.getCheckedRadioButtonId();
        if(selectedID==Easy.getId()){
            yougaDB.saveSettingMode(0);
        } else if(selectedID==Intermediate.getId()){
            yougaDB.saveSettingMode(1);
        } else if(selectedID==Difficult.getId()){
            yougaDB.saveSettingMode(2);
        }
    }

    //set radio button
    private void setRadioButton(int mode){
        if(mode==0){
            Group.check(R.id.rdiEasy);// why the fuck is R in red i will kill you
        } else if(mode==1){
            Group.check(R.id.rdiIntermediate);// why the fuck is R in red i will kill you
        } else if(mode==2){
            Group.check(R.id.rdiDiffult);// why the fuck is R in red i will kill you
        }

    }
}

ViewPose:

package mo.youga;


import java.util.*;
import java.io.*;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;

import mo.youga.Database.YougaDB;
import mo.youga.Utilities.Random;

public class ViewPose extends AppCompatActivity {

    //AD MOB
    private RewardedVideoAd RewardedVideoAd;
    //AD MOB
    //variables
    int image_id;
    String name;
    TextView timer, title;
    ImageView detail_image;
    Button Start;

    boolean isRunning=false;

    YougaDB yougaDB;

    //on create
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pose);
        //youga db
        yougaDB=new YougaDB(this);

        //toolbar
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //floating action button
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });




        timer=(TextView)findViewById(R.id.timer);
        title=(TextView)findViewById(R.id.title);
        detail_image=(ImageView)findViewById(R.id.detail_image);
        Start=(Button)findViewById(R.id.Start);
        //set on click listener
        Start.setOnClickListener(new View.OnClickListener() {
            //on click
            @Override
            public void onClick(View v) {
               if(!isRunning){
                   Start.setText("Finished");
                   int TimeLimit=0;
                   if(yougaDB.getSettingMode()==0){
                        TimeLimit= Random.TIME_LIMIT_EASY;
                   }else if(yougaDB.getSettingMode()==1){
                       TimeLimit= Random.TIME_LIMIT_INTERMEDIATE;
                   } else if(yougaDB.getSettingMode()==2){
                       TimeLimit= Random.TIME_LIMIT_DIFFICULT;
                   }


                   new CountDownTimer(TimeLimit, 1000){
                       @Override
                       public void onTick(long l){
                           timer.setText("" + 1/1000);
                       }
                        // on finish
                       @Override
                       public void onFinish(){
                           //ADD AD MOBS HERE TO ADD ADVERTS TO MAKE IT BETTER
                           //add advertsisement here to enhance this project
                           Toast.makeText(ViewPose.this, "END", Toast.LENGTH_SHORT).show();
                           finish();

                           }//on finish end

                   }.start();
               } else{
                   Toast.makeText(ViewPose.this, "END", Toast.LENGTH_SHORT).show();
                   finish();
               }

                isRunning=!isRunning;

            }
        });


        timer.setText(" ");
        if(getIntent() !=null){
             image_id=getIntent().getIntExtra("image_id", -1);
             name=getIntent().getStringExtra("name");
             detail_image.setImageResource(image_id);
             title.setText(name);
        }
    }



}

ListOfPoses:

package mo.youga;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.*;
import java.io.*;

import mo.youga.Adapter.RecyclerViewAdapter;
import mo.youga.ModelPackage.Poses;

public class ListOfPoses extends AppCompatActivity {


    List poseList= new ArrayList<>();
    RecyclerView.LayoutManager layoutManager;
    RecyclerView recyclerView;
    RecyclerViewAdapter adapter;

    //on create
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_of_poses);

        initData();//call to outer method

        recyclerView=(RecyclerView)findViewById(R.id.list_p);
        adapter=new RecyclerViewAdapter(poseList,getBaseContext());
        layoutManager=new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

    }

    //in it data
    private void initData(){

        poseList.add(new Poses(R.drawable.alternativeheadstand, "Alternative Headstand Pose"));
        poseList.add(new Poses(R.drawable.backwardstriangle, "Backwards Triangle Pose"));
        poseList.add(new Poses(R.drawable.bentlegupwardfacingdog, "Bent Leg Upward Facing Dog Pose"));
        poseList.add(new Poses(R.drawable.bowedtree, "Bowed Tree Pose"));
        poseList.add(new Poses(R.drawable.compactcompass, "Compact Compass Pose"));
        poseList.add(new Poses(R.drawable.cowface, "Cow Face Pose"));
        poseList.add(new Poses(R.drawable.crow, "Crow Pose"));
        poseList.add(new Poses(R.drawable.extendedhandtobigtoe, "Extended Hand To Big Toe Pose"));
        poseList.add(new Poses(R.drawable.fishoutofheroprayer, "Fish Out Of Hero Prayer Pose"));
        poseList.add(new Poses(R.drawable.forwardlungeprayer, "Forward Lunge Prayer Pose"));
        poseList.add(new Poses(R.drawable.frog, "Frog Pose"));
        poseList.add(new Poses(R.drawable.fullboat, "Full Boat Pose"));
        poseList.add(new Poses(R.drawable.fullsplitarmsextended, "Full Split Arms Extended Pose"));
        poseList.add(new Poses(R.drawable.halfboat, "Half Boat Pose"));
        poseList.add(new Poses(R.drawable.handstotoes, "Hand To Feet Lotus Pose"));
        poseList.add(new Poses(R.drawable.handtofeetlotus, "Hands To Toes Pose"));
        poseList.add(new Poses(R.drawable.kingpigeon, "King Pigeon Pose"));
        poseList.add(new Poses(R.drawable.locust1, "Locust 1 Pose"));
        poseList.add(new Poses(R.drawable.locust2, "Locust 2 Pose"));
        poseList.add(new Poses(R.drawable.lordofdancers1, "Lord Of Dancers 1 Pose"));
        poseList.add(new Poses(R.drawable.lordofdancers2, "Lord Of Dancers 2 Pose"));
        poseList.add(new Poses(R.drawable.lotus, "Lotus Pose"));
        poseList.add(new Poses(R.drawable.revolvedextendedsideangle, "Revolved Extended Side Angle Pose"));
        poseList.add(new Poses(R.drawable.revolvedheadtoknee, "Revolved Head To Knee Pose"));
        poseList.add(new Poses(R.drawable.royalpigeon, "Royal Pigeon Pose"));
        poseList.add(new Poses(R.drawable.sage1, "Sage 1 Pose"));
        poseList.add(new Poses(R.drawable.sage2, "Sage 2 Pose"));
        poseList.add(new Poses(R.drawable.scorpon, "Scorpion Pose"));
        poseList.add(new Poses(R.drawable.seatedtwist, "Seated Twist Pose"));
        poseList.add(new Poses(R.drawable.seatedwindrelease, "Seated Wind Release Pose"));
        poseList.add(new Poses(R.drawable.sidecrab, "Side Crab Pose"));
        poseList.add(new Poses(R.drawable.sidewardsplitlegged, "Sideward Split Legged Pose"));
        poseList.add(new Poses(R.drawable.spinaltwist, "Spinal Twist Pose"));
        poseList.add(new Poses(R.drawable.splitleggedabdomentwist1, "Spinal legged Abdomen Twist 1 Pose"));
        poseList.add(new Poses(R.drawable.splitleggedabdomentwist2, "Spinal legged Abdomen Twist 2 Pose"));
        poseList.add(new Poses(R.drawable.splitstancebow, "Split Stance Bow Pose"));
        poseList.add(new Poses(R.drawable.supercow, "Super Cow Pose"));
        poseList.add(new Poses(R.drawable.tree, "Tree Pose"));
        poseList.add(new Poses(R.drawable.upwardfacingtwofootstaff, "Upward Facing Two Foot Staff Pose"));
        poseList.add(new Poses(R.drawable.warrior1, "Warrior 1 Pose"));
        poseList.add(new Poses(R.drawable.wheel, "Wheel Pose"));
        poseList.add(new Poses(R.drawable.wideleggedabdomentwist, "Wide Legged Abdomen Twist Pose"));
    }
}

DailyTraining:

package mo.youga;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import mo.youga.Database.YougaDB;
import mo.youga.ModelPackage.Poses;
import mo.youga.Utilities.Random;
import mo.youga.Utilities.Random;

import static android.support.v7.widget.AppCompatDrawableManager.get;


public class DailyTraining extends AppCompatActivity {
    //variables or fields
    Button Start;
    ImageView image;
    TextView GetReady, Countdown, Timer, Name;
    ProgressBar progressBar;
    LinearLayout layoutGetReady;
    int id=0, timelimit=0;
    List list=new ArrayList<>();// ERROR:Pose<> FIX: Poses<>
    YougaDB yougaDB;

    //on create
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daily__training);

        initData();
        //calling db
        yougaDB=new YougaDB(this);

        //dead code
        /*
        if(yougaDB.getSettingMode()==0){
            timelimit= Common.TIME_LIMIT_EASY;
        } else if(yougaDB.getSettingMode()==1){
            timelimit= Common.TIME_LIMIT_INTERMEDIATE;
        } else if(yougaDB.getSettingMode()==2){
            timelimit= Common.TIME_LIMIT_DIFFICULT;
        }
        */

        Start=(Button)findViewById(R.id.Start);
        image=(ImageView)findViewById(R.id.detail_image);
        GetReady=(TextView)findViewById(R.id.GetReady);
        Countdown=(TextView)findViewById(R.id.Countdown);
        Timer=(TextView)findViewById(R.id.timer);
        Name=(TextView)findViewById(R.id.title);
        //layout
        layoutGetReady=(LinearLayout)findViewById(R.id.layout_get_ready);
        //progress
        progressBar=(MaterialProgressBar)findViewById(R.id.progressBar);
        //setting data
        progressBar.setMax(list.size());

        // set on click listener
       Start.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {

               if(Start.getText().toString().toLowerCase().equals("Start ")){

                   showGetReady();//transferred on to method
                   Start.setText("Done");

               } else if(Start.getText().toString().toLowerCase().equals("Done ")){
                   if(yougaDB.getSettingMode()==0){
                       poseEasyCountDown.start();
                   } else if(yougaDB.getSettingMode()==1){
                       poseIntermediateCountDown.start();
                   } else if(yougaDB.getSettingMode()==2){
                       poseDifficultCountDown.start();
                   }

                    breakCountDown.cancel();//allows user to cancel out of count down timer


                    if(id

Calendar:

package mo.youga;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

import mo.youga.Database.YougaDB;
//import mo.youga.Custom;
public class Calendar extends AppCompatActivity {

    //variables
    MaterialCalendarView materialCalendarView;
    HashSet list=new HashSet<>();
    YougaDB yougaDB;

    // on create
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);
        YougaDB yougaDB=new YougaDB(this);
        materialCalendarView=(MaterialCalendarView)findViewById(R.id.calendar);//ERROR: R
        ListworkoutDays=yougaDB.getWorkoutDays();//get data from db and convert it into hashset
        HashSetconversion=new HashSet<>();
        for(String value: workoutDays){
            conversion.add(CalendarDay.from(new Date(Long.parseLong(value))));
        }//for
        materialCalendarView.addDecorator(new WorkoutDoneDecorator(conversion));//ERROR: Custom FIX:
    }//oncreate

   private class WorkoutDoneDecorator implements DayViewDecorator {

     public WorkoutDoneDecorator(HashSet conversion) {

      }

        @Override
        public boolean shouldDecorate(CalendarDay day) {
            return false;
        }

        @Override
        public void decorate(DayViewFacade view) {

        }
    }
}

AlarmNotificationReceiver:

package mo.youga;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

public class AlarmNotificationReceiver extends BroadcastReceiver {

    //on receive
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "CHANNEL_ID");
        //NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
        builder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.io_launcher_round)
                .setTicker("abcd")//define
                .setContentTitle("Time")
                .setContent("Training Time")
                .setContentInfo("Information");

               // NotificationManager notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                //notificationManager.notify(1,builder.build());

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build());

    }
    //set when
    public void setWhen(long when) {
        when=when;
    }
}

Random:

package mo.youga.Utilities;

public class Random {

    public static final int TIME_LIMIT_EASY=10000;
    public static final int TIME_LIMIT_INTERMEDIATE=20000;
    public static final int TIME_LIMIT_DIFFICULT=30000;




}

Poses:

package mo.youga.ModelPackage;

public class Poses {

    private int image_id;
    private String name;

    public Poses(int image_id, String name){
    this.image_id=image_id;
    this.name=name;
    }

    public int getImage_id(){
        return image_id;
    }

    public void setImage_id(int image_id) {
        this.image_id = image_id;
    }

    public String getName(){
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



}

ItemClickListener:

package mo.youga.Interface;

import android.view.View;

public interface ItemClickListener {

    void onClick(View view, int position);
}

YougaDB:

package mo.youga.Database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;


import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

import java.util.ArrayList;
import java.util.List;

public class YougaDB extends SQLiteAssetHelper {

    private static final String DB_NAME="Youga.db";
    private static final int DB_VER=1;

    //youga db
    public YougaDB(Context context) {
        super(context, DB_NAME, null, DB_VER);
    }

    //get setting mode
    //function to INSERT data into table
    public int getSettingMode(){
        SQLiteDatabase db= getReadableDatabase();
        SQLiteQueryBuilder qb= new SQLiteQueryBuilder();
        String [] sqlSelect={"Mode"};
        String sqlTable="Setting";
        qb.setTables(sqlTable);
        Cursor cursor = qb.query(db,sqlSelect,null,null,null,null,null);
        cursor.moveToFirst();
        return cursor.getInt(cursor.getColumnIndex("Mode"));
    }

    //save setting mode
    //function to SAVE data into table
    public void saveSettingMode(int value){
        SQLiteDatabase db=getReadableDatabase();
        String query= "UPDATE Setting SET Mode = "+ value;
        db.execSQL(query);
    }

    // get workout days
    //reading and writing to new table
    public List getWorkoutDays(){
        SQLiteDatabase db= getReadableDatabase();
        SQLiteQueryBuilder qb= new SQLiteQueryBuilder();

        String [] sqlSelect={"Day"};
        String sqlTable="Workout Days";
        qb.setTables(sqlTable);
        Cursor cursor = qb.query(db,sqlSelect,null,null,null,null,null);

        //list interface implementation
        List result=new ArrayList();
        if(cursor.moveToFirst()){
            do {
                result.add(cursor.getString(cursor.getColumnIndex("Day")));
            } while(cursor.moveToNext());{// <--ADDED A ; HERE IF ERROR DELETE ;

            }
        }

        return result;

    }

    // save day
    //setting mode for new table
    public void saveDay(String value){
        SQLiteDatabase db=getReadableDatabase();
        String query= String.format("INSERT INTO WorkoutDays(Day) VALUES('%s'):", value);
        db.execSQL(query);
    }

}

WorkoutDoneDecorator:

package mo.youga.Custom;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;

import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import java.util.*;
import java.io.*;
import java.util.HashSet;

public class WorkoutDoneDecorator implements DayViewDecorator {

    HashSetlist;
    ColorDrawable colorDrawable;

    //constructor
    public WorkoutDoneDecorator(HashSetlist){
        this.list=list;
        colorDrawable=new ColorDrawable(Color.parseColor("#111111"));
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return list.contains(day);
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.setBackgroundDrawable(colorDrawable);
    }
}

RecyclerViewAdapter:

package mo.youga.Adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.widget.Toast;

//import own classes
import mo.youga.Interface.ItemClickListener;
import mo.youga.ModelPackage.Poses;
import mo.youga.R;//FUCKING BASTARD I WILL KILL YOU FOR CAUSING AN ERROR
import mo.youga.ViewPose;

import java.util.*;
import java.io.*;

//recycler view holder

class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public ImageView image;
    public TextView text;
    private ItemClickListener itemClickListener;

    public RecyclerViewHolder(View itemView){
        super(itemView);
        image=(ImageView)itemView.findViewById(R.id.ex_img);
        text=(TextView)itemView.findViewById(R.id.ex_name);
        itemView.setOnClickListener(this);
    }

    //set item click listener
    public void setItemClickListener(ItemClickListener itemClickListener){
        this.itemClickListener=itemClickListener;
    }


    //on click
    @Override
    public void onClick(View view){
        itemClickListener.onClick(view,getAdapterPosition());
    }

}

//recycler view adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter{// timestamp- 17:00

    private ListposeList;
    private Context context;

    public RecyclerViewAdapter(ListposeList,Context context ){
        this.poseList=poseList;
        this.context=context;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        LayoutInflater inflater=LayoutInflater.from(parent.getContext());
        View itemView=inflater.inflate(R.layout.item_pose,parent,false);
        return new RecyclerViewHolder(itemView);
    }//recycler view holder

    //on bind view holder
    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position){
        holder.image.setImageResource(poseList.get(position).getImage_id());
        holder.text.setText(poseList.get(position).getName());

        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent=new Intent(context, ViewPose.class);
                intent.putExtra("image", poseList.get(position).getImage_id());
                intent.putExtra("name", poseList.get(position).getName());
                context.startActivity(intent);
            }
        });
    }//on bind view holder

    //get item count
    public int getItemCount(){
        return poseList.size();
    }//get item count



}//recycler view adapter ends

All topic

How to transacting with a smart contract using web3j in Android?

i used web3j to Transacting with a smart contract.
this is my Contract function which i want to intertact with.

function usersRegister(string _id, string _password){
    Equipment e = equipments[msg.sender];
    e.users[e.usersNum++] = User({id: _id, password: _password, registerTime: now});
}

and this is my code in Android using web3j

Web3j web3j = Web3jFactory.build(new HttpService(url));
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                        equipmentAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
                BigInteger nonce = ethGetTransactionCount.getTransactionCount();
BigInteger gasPrice = Contract.GAS_PRICE;
BigInteger gasLimit = Contract.GAS_LIMIT;

List inputParameters = new ArrayList<>();
Type usersId = new Utf8String(_usersId);
Type usersPassword = new Utf8String(_usersPassword);
inputParameters.add(usersId);
inputParameters.add(usersPassword);
Function function = new Function("usersRegister",
                        inputParameters,
                        Collections.>emptyList());
String functionEncoder = FunctionEncoder.encode(function);
Transaction transaction = Transaction.createFunctionCallTransaction(
                        equipmentAddress, nonce, gasPrice,
                        gasLimit, contractAddress, new BigInteger("0"),
                        functionEncoder);
EthSendTransaction transactionResponse =
                 web3j.ethSendTransaction(transaction).sendAsync().get();

but i get “null” in transactionResponse.getTransactionHash()

someone know what’s wrong with my code?thx for help 😡

All topic