Well I am using google github on firebase database. There are people comments if users like others comment, they can give a star (like). on the other hand I want to make a page which is showing only top comments which are upped. if I use this query:

Sample code is given below-:

package com.google.firebase.quickstart.database.fragment;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.Query;

    public class MyTopPostsFragment extends PostListFragment {

        public MyTopPostsFragment() {}

        @Override
        public Query getQuery(DatabaseReference databaseReference) {
            // [START my_top_posts_query]
            // My top posts by number of stars
            String myUserId = getUid();
            Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
                    .orderByChild("starCount");
            // [END my_top_posts_query]

            return myTopPostsQuery;
        }
    }

    Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
                    .orderByChild("starCount");

it will return all times top comments. how specify such as top comments week or day. also there a timestamp in my datasnapshoot

I am trying to align a button to bottom of screen but it is not moving. The last button, with id=button 1, is the button in question. I want this button to align right at bottom of screen, but looks like, some combination of the attributes of nested arrays no letting it happen.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.crackit.crackit.startQuiz1">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40dp"/>
<LinearLayout
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal"
android:weightSum="2">
<Button
android:id="@+id/radio0"
android:layout_weight="1"
android:layout_height="140dp"
android:layout_width="140dp"
/>

<Button
android:id="@+id/radio1"
android:layout_weight="1"
android:layout_height="140dp"
android:layout_width="140dp"
/>

</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="@+id/radio2"
android:layout_weight="1"
android:layout_height="140dp"
android:layout_width="140dp"
/>

<Button
android:id="@+id/radio3"
android:text="Android"
android:layout_weight="1"
android:layout_height="140dp"
android:layout_width="140dp"
/>
</LinearLayout>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#0000FF"
android:onClick="NextQuestion"
android:layout_gravity="bottom"
android:textColor="#FFFFFF"
android:text="Next" />
</LinearLayout>
</LinearLayout>

I am trying to align a button to bottom of screen but it is not moving. The last button, with id=button 1, is the button in question. I want this button to align right at bottom of screen, but looks like, some combination of the attributes of nested arrays no letting it happen.

I am building a website which has a single page app frontend that connects to a REST API from the backend. I also want others to be able to write programs for this website.

It seems like providing public access to the same API I build my frontend in would be useful. There would only be one API to maintain and I know every single feature of the website is available for 3rd parties.

Are there any cons to this approach?

Some things that come to mind is letting 3rd parties use the same API as I use myself for the frontend might hold back development as new features and changes can't be released right away. Another is that I'd probably want to have a system that allows users to give permissions to 3rd party tool such as allowing making posts but disallowing changing user settings. I'm not sure how well this would work while sharing the same API.

I was wondering if someone could tell which approach is better: serving HTML/JavaScript/CSS files from a hosted web app vs locally from file://. I'm currently running a Webpack project backed by Firebase that generates a SPA with a HTML file, a JavaScript bundle, and a CSS bundle. So far I have:

Hosted:

  • Less responsive (probably not noticeable if all the files are downloaded on initial load but would be impacted by slow Wi-Fi).
  • Less security issues (easier third-party authentication, etc).
  • Harder to pass Apple App Store review (assumption).
  • Additional server costs.
  • Orchestration (e.g. change in plugin and code would mean mobile app and web app would need to update at same time).
  • Updates via deploying changes to web app.

Local:

  • More security issues (harder third-party authentication, configuration changes due to local hosting, etc).
  • Updates via code push plugin.

In general, I'm looking to find out which approach would provide the best experience for my users.

I am working on a auto fill app which the user will enter their information in the text field and once they open a certain website, that information in which they entered in the text field will be automatically filled out.

I have seen a couple of codes on here but I think they’re outdated.

My first view controller is where the user enters their info. (See picture). Next view controller will be the UIWebView. How to I connect the Button to the UIWebView and what is the code for the JavaScript to call the textfield?

Here is the code I tried

let js = "var myelement = document.getElementById(\"test\");myelement.innerHTML= \"New Text\";" webView.evaluateJavaScript(js, completionHandler: nil) ]1

Where would the TextField go in? Where do I declare the textfield(viewController or the WebViewController)?

I have one viewPager in anko and i wanna know how to get current page data when i click on view pager item.

val mainPager = viewPager {
                        id = R.id.image_pager
                        backgroundColor = Color.BLACK
                        onClick { 
                            // need to know current page data from adapter
                        }
                    }.lparams(matchConstraint, context.displayMetrics.widthPixels)

My Activity Login have edittext's value first entered by username and second value by password What I want do is ... I'm trying to pass this values of editText from Activity Class to nonActivityClass(java Class) .

Does exist any way to do this.

I'm using Google Fit API to develop a fitness app.

Take a look at this picture of a google fit recorded session: here

I would like to know if it's possible to get the map displayed at the top of the screen. In fact, I know how to call the History API to get sessions but I can't figure out how to get the map displaying the route taken during the activity by the user.

I found this possible duplicate topic (unanswered): Google fit api: get distance/calories/speed when tracking running/biking

Any help would be appreciated !

I have a project that have a gridview inside a fragment showing a list of games that clicking in each will open a new fragment showing the guide for the game.

How can I manage this array from a server to when I upload more images it updates the app gridview with new images?

Actually, what I need is:

  • Download and show the images inside the gridview.
  • Add images directly to a server, make the app listen the server, when new images were added the app update the list of image and title of the game and show automatically in the gridview.(if possible)

Gridview

public class GridGameListFragment extends Fragment {

    private Context context;
    private LayoutInflater inflater;

    GridView gridView;


    public GridListaJogosFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.grid_lista_jogos_fragment, container, false);

      gridView = (GridView) view.findViewById(R.id.gridview_xml);

      CustomGridAdapterGameList adapter = new CustomGridAdapterGameList(getActivity());

       gridView.setAdapter(adapter);

       gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {



               FragmentManager fragmentManager = getFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

               GuideFragment guideFragment = new GuideFragment();

               fragmentTransaction.add(R.id.rl_lista_jogos_activity_xml, guideFragment);
                fragmentTransaction.addToBackStack(null);


               fragmentTransaction.commit();

           }
       });

        return view;
    }

}

========================

public class CustomGridAdapterGameList extends BaseAdapter {

    private String[] titles = { "Final Fantasy 7",
            "Final Fantasy 8",
            "Final Fantasy 9"

    };
    private int[] covers = { R.drawable.ff7_ps1,
            R.drawable.ff8_ps1,
            R.drawable.ff9_ps1,
    };

    private Context context;
    private LayoutInflater inflater;

    public CustomGridAdapterGameList(Context context){

        this.context = context;

    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public Object getItem(int position) {
        return titles.length;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View gridview = convertView;

        if(convertView == null){

            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            gridview = inflater.inflate(R.layout.custom_gridview__lista_jogos_layout, null);
        }else{
            gridview= convertView;
        }

        TextView textView = gridview.findViewById(R.id.textview_custom_grid_xml);
        ImageView imageView = gridview.findViewById(R.id.imageview_custom_grid_xml);

        textView.setText(titles[position]);
        imageView.setImageResource(covers[position]);

        return gridview;
    }
}

I've got an xml file in my AIR app and I'm trying to determine his size. Here's what I did :

var file:File = File.applicationStorageDirectory.resolvePath("horaires3.xml");
trace(file.url); //path to the file
trace(file.size); 

But I've got this error : Error #3003: File or directory does not exist.

The file.url is working, but the file.size is throwing the error..

I am working on an example of JNI in Android Studio, the goal it to generate a Random Value and pass it to a native function which will calculate its Square and return the result in this format ( Number/Square ).

I am passing the jint number as a parameter of the function, but the result is totally wrong (the result displayed is totaly wrong). Here is my code :

Button Generating the number and calling the native function :

Button ButtonP = (Button)findViewById(R.id.button3);
        ButtonP .setOnClickListener(
                new View.OnClickListener()
                {
                    public void onClick(View view)
                    {
                        Random r = new Random();
                        Integer valeur = 1 + r.nextInt(10 - 1);
                        Log.i("Tag", "Random Value BARRAK " + valeur);
                        TextView tv = (TextView) findViewById(R.id.sample_text);
                        tv.setText(stringFromJNIStop(valeur));
                    }
                });

The Native function:

public native String stringFromJNIStop(Integer nombre);

The implementation of the function in the cpp file:

extern "C"
JNIEXPORT jstring JNICALL
Java_fr_utbm_testjniapplication1_MainActivity_stringFromJNIStop(
        JNIEnv *env,
        jobject, /* this */
        jint nombre) {
    jint CarreNombre = nombre*nombre;

    //Convertir le carré en un jstring
    char bufCarreNombre[64];
    sprintf(bufCarreNombre, "%d", CarreNombre);  // error checking omitted
    jstring jStringCarre = (*env).NewStringUTF(bufCarreNombre);
    //Le convertir en un char *
    const char *strCarre= (*env).GetStringUTFChars(jStringCarre,0);

    //Convertir le nombre en un jstring
    char bufNombre[64];
    sprintf(bufNombre, "%d", nombre);  // error checking omitted
    jstring jStringNombre = (*env).NewStringUTF(bufNombre);
    //Le convertir en char *
    const char *strNombre= (*env).GetStringUTFChars(jStringNombre,0);

    //Concaténer les deux
    char *concatenated;
    concatenated = (char *) malloc(strlen(strNombre) + strlen("/") + strlen(strCarre) + 1);
    strcpy(concatenated, strNombre);
    strcat(concatenated, "/");
    strcat(concatenated, strCarre);

    /* Create java string from our concatenated C string */
    jstring retval = (*env).NewStringUTF(concatenated);

    //need to release this string when done with it in order to
    //avoid memory leak
    (*env).ReleaseStringUTFChars(jStringNombre,strNombre);
    (*env).ReleaseStringUTFChars(jStringCarre,strCarre);
    /* Free the memory in concatenated */
    free(concatenated);
    return retval;

}

Hi I've been working on a simple Chronometer app that stores lap times in a Database. I've created a Database Helper class. When I try to insert the data from my activity I get an error saying that there is no such table created. I have removed some of the code from the activity here for simplicity(the code for buttons, etc) At first i though there is a problem with using constants but I have created the table without any of them and I get the same error.

DatabaseHelper.java

package com.example.andrei.gymhelp;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseHelper extends SQLiteOpenHelper {

private static final String TAG = "SQLMessage";
private static final String DATABASE_NAME = "StoredResults.db";
private static final int DATABASE_VERSION = 2;
private static DatabaseHelper mDatabaseInstance = null;
private Context mContext;


public static DatabaseHelper newInstance(Context context){
    //first check to see if the database helper
    //member data is null
    //create a new one if it is null

    if (mDatabaseInstance == null){
        mDatabaseInstance = new DatabaseHelper(context.getApplicationContext());
    }

    //either way we have to always return an instance of
    //our database class each time this method is called
    return mDatabaseInstance;
}



public DatabaseHelper(Context context) {

    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    mContext = context;
}
private static final String CREATE_TABLE_LAPS = "create table results_table "
        + "("
        + "_id" + " integer primary key autoincrement, "
        + "timestamp" + " text not null, "
        + "laps" + " text not null, "
        + ")";
 //private static final String CREATE_TABLE_LAPS =
//        "CREATE TABLE " + Constants.LAPS_TABLE + "("
//                + Constants.COLUMN_ID + " INTEGER PRIMARY KEY 
AUTOINCREMENT,"
//                + Constants.COLUMN_TIMESTAMP + " TEXT NOT NULL, "
//                + Constants.COLUMN_LAPS + " TEXT NOT NULL, "
//                + ")";

@Override
public void onCreate(SQLiteDatabase db) {
   try{
       db.execSQL(CREATE_TABLE_LAPS);
       Log.d(TAG, "TABLE WAS CREATED ");
   } catch (SQLException e) {
       Log.d(TAG, " Error create database " + e.getMessage());
   }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + Constants.LAPS_TABLE);
    onCreate(db);

 }
}

TimerActivity.java

package com.example.andrei.gymhelp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;
import java.util.Hashtable;

public class TimerActivity extends AppCompatActivity {

private Context context;
private TextView timer;
private Button btnStart;
private Button btnLap;
private Button btnStop;
private Button btnSave;
private TextView laps;
private int lapsCounter = 1;
private ScrollView scrollLaps;
private boolean saved = false;
private String savedLaps = "";
private static final String TAG = "MESSAGE";
Date dateAndTime = new Date();
private String sequenceTimestamp;


private DatabaseHelper mDBHelper;
private SQLiteDatabase mDatabase;

private Chronometer mainChronometer;
private Thread threadChrono;

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


    mDBHelper = new DatabaseHelper(this);
    mDatabase  = mDBHelper.getWritableDatabase();





    btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mainChronometer != null) {

                Context context = getApplicationContext();
                CharSequence text = getString(R.string.chrono_not_stopped);
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

            }else{
                if (!saved) {

                    Log.v(TAG, "LAPS = " + savedLaps);
                    Log.v(TAG, String.valueOf(System.currentTimeMillis()));
                    saved = true;

                    Context context = getApplicationContext();
                    CharSequence text = getString(R.string.saved_toast);
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    sequenceTimestamp = (String) DateFormat.format("hh:mm:ss dd-MM-yyyy", dateAndTime.getTime());

                    saveResultsToDatabase(sequenceTimestamp, savedLaps);
                    Log.v(TAG, sequenceTimestamp);

                    } else {
                        Context context = getApplicationContext();
                        CharSequence text = getString(R.string.alreadysaved_toast);
                        int duration = Toast.LENGTH_SHORT;

                        Toast toast = Toast.makeText(context, text, duration);
                        toast.show();
                    }
            }
        }
    });

}

public void updateTimer(final String time){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            timer.setText(time);
        }
    });
}
public void saveResultsToDatabase(String timestamp,String stringOfLaps) {
    //if (mDatabase != null) {
        //prepare the transaction information that will be saved to the database
        ContentValues values = new ContentValues();
        values.put(Constants.COLUMN_TIMESTAMP, timestamp);
        values.put(Constants.COLUMN_LAPS, stringOfLaps);

        try {


            Log.i(TAG,"SAVE RESULTS WAS CALLED");
            mDatabase.insert(Constants.LAPS_TABLE, null, values);

            mDatabase.close();
        }catch (SQLException e){
            Log.d(TAG,e.getMessage());
        }
    //}
}

}

Error

01-08 22:09:09.081 10656-10656/com.example.andrei.gymhelp E/SQLiteLog: (1) 
01-08 22:09:09.083 10656-10656/com.example.andrei.gymhelp E/SQLiteDatabase: Error inserting timestamp=10:09:04 08-01-2018 laps=Lap 1: 00:00:00:786|Lap 2: 00:00:01:283|Lap 3: 00:00:01:756|Lap 5: 00:00:02:177|
                                                                        android.database.sqlite.SQLiteException: no such table: results_table (Sqlite code 1): , while compiling: INSERT INTO results_table(timestamp,laps) VALUES (?,?), (OS error - 2:No such file or directory)
                                                                            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:910)
                                                                            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:521)
                                                                            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
                                                                            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
                                                                            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1725)
                                                                            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1593)
                                                                            at com.example.andrei.gymhelp.TimerActivity.saveResultsToDatabase(TimerActivity.java:186)
                                                                            at com.example.andrei.gymhelp.TimerActivity$4.onClick(TimerActivity.java:150)
                                                                            at android.view.View.performClick(View.java:5646)
                                                                            at android.view.View$PerformClick.run(View.java:22459)
                                                                            at android.os.Handler.handleCallback(Handler.java:761)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                            at android.os.Looper.loop(Looper.java:156)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

Is it possiable to use reflection to access a object's private field and call a public methods on this field?

i.e

class Hello {
   private World word
}

class World {
   public BlaBlaBla foo()
}

Hello h = new Hello()

World world = reflect on the h


// And then 

world.foo()

I am wondering how to show searchview in actionbar only in parent fragment. For now, when I submit a search from searchview in actionbar and go to next fragment, I still can see the searchview in my child fragment. Any suggestions to fix that? Thanks.

For now, in my parent class

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // Inflate the options menu from XML
    inflater.inflate(R.menu.homesearchbar, menu);
    super.onCreateOptionsMenu(menu,inflater);

    // Get the SearchView and set the searchable configuration
    SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setMaxWidth(Integer.MAX_VALUE);
    searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Bundle bundle = new Bundle();
            bundle.putString("HomeToSearch_keyword", query);
            SearchVC searchVC = new SearchVC();
            searchVC.setArguments(bundle);
            getFragmentManager().beginTransaction().add(R.id.HomeVC_frameChildFragment, searchVC)
                    .addToBackStack(null)
                    .commit();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
}

homesearchbar.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:title=""
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always"/>
</menu>

Yes another one.

Sadly none of the others helped. Perhaps I missed something I don't think I did. Essentially nothing happens when I press on any of them no highlighting no nothing. START and BEFORE CLICK will show in the logs, the rest do not. Here is a sample of the code if you need the rest let me know.

 /***
 * https://www.youtube.com/watch?v=Z7oekIFb7fA
 */
private void newSheetWeapon() {
    Log.i("newSheetWeapon: ", "START");
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.custom_dialogue, null);

    ListView listView = (ListView) row.findViewById(R.id.custom_dialogue_listView);
    //listView.setClickable(true);
    listView.setAdapter(new AttackDialogCustomAdapter(getContext()));
    Log.i("newSheetWeapon: ", "BEFORE CLICK");
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("newSheetWeapon: ", "CLICKED");
            Toast.makeText(getContext(), "HELLO", Toast.LENGTH_LONG).show();
            Log.i("newSheetWeapon: ", "AFTER CLICK TOAST");
            //String.valueOf(position)
        }
    });
    builder.setView(row);
    AlertDialog dialog = builder.create();
    dialog.show();
}

custom_dialogue.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/custom_dialogue_listView"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

I was able to generate jacoco test report before untill recently I found out that the normal coverage.ec file got renamed to Nexus_5X_API_26(AVD) - 8.0.0-coverage.ec(looks like device name + coverage.ec), thus my gradle script wasn't able to locate it unless I manually update to use the new file name.

Is there a way to get the device name from gradle script so when I run the task to combine coverage report it will be able to find the coverage file.

Good day,

I'm working on an assignment for my university right now. Considering I had absolutely no idea about Android or Java and was "thrown" into this, I think I'm handling quite well.

Now to a problem I can't solve myself, sadly:

I have a table where a worker can insert a start and an end time. Now I want him to be able to insert the time "normal", like 13:46, 14:23 etc. or in decimal style, like 13,99, 14,50 etc.

I want my App to be able to "see" the time as x:y or x,b

Important: The app should discern if it is a comma or a colon and then check

if 0<=x<24 and 00<=y<60 or 00<=b<99

Is there a way to do this? Or should I just stay with the x:y format and then let the app check if 0<=x<24 and 00<=y<60

Thank you very much

We are using Git and want to add a server side post-receive hook that posts events to our bug tracking system.

In our company, the Git server is managed by IT, and the server of the bug tracking system is managed by us, developers. Because developers don't have access to IT's servers, if we made updates to the git hook, we have to ask IT to upload the new revision. Someone suggests that in order to avoid bothering IT, the hook, instead of running complex logic, simply passes raw parameters to a middle layer managed by us, and the middle layer does the heavy passing and complex logic, then posts events to the API endpoint of the bug tracking system, as illustrated by the red flow in the figure.

enter image description here

Do you agree it's a good strategy? I slightly feel the middle layer adds maintenance cost, there should be some workaround to the lack of control of IT's server. How will you deal with this situation?

I don't know what proper tags are for this question. Feel free to add.

enter image description here

I've got a stack view and I'm wanting when the user clicks on one of the buttons a little "bar" view centers underneath it (the view is outside of the stack view). I had this working before I layed out the buttons with autolayout by just setting

movableView.center.x = newView.center.x

and animating it. Now with the buttons in the stack view the movableView's center X does not line up with the buttons' center x's. It's like 1/3 way off centered.

The movable view itself has no autolayout on it.

What is the cause of this and how can I align the center x of views that have auto layout in play?

I have a function that makes a call and waits for a response from a server. I would like to show the activity indicator before a request and hide it after the answer to this same function. Why? To avoid code repetition. I will have calls to the server in other actions.

It works the way it is right now: manually calling the start and stop animation on the login button.

To test the indicator, I added sleep on the server.

Question: How can I show/hide the indicator for every call to the server?

Button on login view:

@IBAction func btnLog2(_ sender: Any) {

    DispatchQueue.main.async(execute: {
        customActivityIndicatory(self.view, startAnimate: true)
    })

    let user = User(email: login_email.text!, password : login_password.text!)

    var jsonData = Data()
    let jsonEncoder = JSONEncoder()
    do {
        jsonData = try jsonEncoder.encode(user)
    }
    catch {
    }

    makeRequestPost(endpoint: "http://blog.local:4711/api/login",
                    requestType: "POST",
                    requestBody: jsonData,
                    completionHandler: { (response : ApiContainer<Login>?, error : Error?) in
                        if let error = error {
                            print("error calling POST on /todos")
                            print(error)
                            return
                        }

                        DispatchQueue.main.async(execute: {
                            customActivityIndicatory(self.view, startAnimate: false)
                        })

                        let a = (response?.result[0])!
                        let b = (response?.meta)!

                        if(b.sucess == "yes") {
                            DAKeychain.shared["email"] = (user.email) // Store
                            DAKeychain.shared["token"] = (a.token) // Store
                            DispatchQueue.main.async(execute: {
                                let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "tabBarClients") as UIViewController

                                self.present(viewController, animated: false, completion: nil)
                            })
                        }
                        else
                        {
                            DispatchQueue.main.async(execute: {
                                let myAlert = UIAlertController(title: "Error", message: "Invalid E-mail or Password", preferredStyle: .alert)
                                let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
                                myAlert.addAction(okAction)

                                self.present(myAlert, animated: true, completion: nil)
                            })
                        }
    } )


}

request func

func makeRequestPost<T>(endpoint: String,
                    requestType: String = "GET",
                    requestBody: Data,
                    completionHandler: @escaping (ApiContainer<T>?, Error?) -> ()) {

guard let url = URL(string: endpoint) else {
    print("Error: cannot create URL")
    let error = BackendError.urlError(reason: "Could not create URL")
    completionHandler(nil, error)
    return
}

var urlRequest = URLRequest(url: url)
let session = URLSession.shared
urlRequest.httpMethod = "POST"
urlRequest.httpBody = requestBody
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTask(with: urlRequest, completionHandler: {
    (data, response, error) in
    guard let responseData = data else {
        print("Error: did not receive data")
        completionHandler(nil, error)
        return
    }
    guard error == nil else {
        completionHandler(nil, error!)
        return
    }

    do {
        let response = try JSONDecoder().decode(ApiContainer<T>.self, from: responseData)
        completionHandler(response, nil)
    }
    catch {
        print("error trying to convert data to JSON")
        print(error)
        completionHandler(nil, error)
    }

})
task.resume()

}

function on helper file:

func makeRequestPost<T>(endpoint: String,
                    requestType: String = "GET",
                    requestBody: Data,
                    completionHandler: @escaping (ApiContainer<T>?, Error?) -> ()) {

guard let url = URL(string: endpoint) else {
    print("Error: cannot create URL")
    let error = BackendError.urlError(reason: "Could not create URL")
    completionHandler(nil, error)
    return
}

var urlRequest = URLRequest(url: url)
let session = URLSession.shared
urlRequest.httpMethod = "POST"
urlRequest.httpBody = requestBody
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTask(with: urlRequest, completionHandler: {
    (data, response, error) in
    guard let responseData = data else {
        print("Error: did not receive data")
        completionHandler(nil, error)
        return
    }
    guard error == nil else {
        completionHandler(nil, error!)
        return
    }

    do {
        let response = try JSONDecoder().decode(ApiContainer<T>.self, from: responseData)
        completionHandler(response, nil)
    }
    catch {
        print("error trying to convert data to JSON")
        print(error)
        completionHandler(nil, error)
    }

})
task.resume()

}

I am having issues gracefully handling this error debugDescription: "Expected String value but found null instead." I understand that in my struct that conforms to Codable, my stored property would need to be declared an optional string, as I read in this post

I tried that and still the error occurs. I read also in that post that I could also customize the decoder to replace nil with an empty string. I do not know how to achieve this honestly.

here is my code:

struct Discover: Codable {
    var page: Int
    var totalResults: Int
    var totalPages: Int
    var results: [DiscoverResults]

     enum CodingKeys: String, CodingKey {
        case page
        case totalResults = "total_results"
        case totalPages = "total_pages"
        case results = "results"
    }

}

struct DiscoverResults {
    var title: String
    var releaseDate: String
    var posterPath: String?
    var id: Int
    var genreIds: [Int]
    var poster: UIImage?

     enum CodingKeys: String, CodingKey {
        case title
        case posterPath = "poster_path"
        case releaseDate = "release_date"
        case id
        case genreIds = "genre_ids"
    }
}

extension DiscoverResults: Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        title = try values.decode(String.self, forKey: .title)
        releaseDate = try values.decode(String.self, forKey: .releaseDate)
        posterPath = try values.decode(String.self, forKey: .posterPath)
        id = try values.decode(Int.self, forKey: .id)
        genreIds = try values.decode([Int].self, forKey: .genreIds)
    }
}

extension DiscoverResults: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(posterPath, forKey: .posterPath)
        try container.encode(releaseDate, forKey: .releaseDate)
        try container.encode(id, forKey: .id)
        try container.encode(genreIds, forKey: .genreIds)
    }
}

The posterPath in DiscoverResults is null for some of the movies as I am using a movie api. If the JSON itself is needed I will edit the post.