I tried to give a look on other posts, but I have not found any satisfactory answer yet. I am trying to make a tab layout, where each tab will contain grids. Current is working well when it comes to make grids. But the problem that it is not showing any scroll.

Sharing the complete code :-

Main Activity.java

package abhirojpanwar.tablayout;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar=(Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Wallser");

        ViewPager viewPager=(ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SimpleFragmentPagerAdapter(getSupportFragmentManager(),MainActivity.this));

        TabLayout tabLayout=(TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);


    }
}

Image Adapter :-

package abhirojpanwar.tablayout;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

/**
 * Created by Abhiroj on 3/4/2017.
 */

class ImageAdapter extends BaseAdapter {
    Context context;
    public ImageAdapter(Context context) {
    this.context=context;
    }

    @Override
    public int getCount() {
        return 10;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        if(view==null)
        {
            view= LayoutInflater.from(context).inflate(R.layout.displayimage,viewGroup,false);
        }

        ImageView imageView=(ImageView) view.findViewById(R.id.image);

        Log.d("Image Adapter","position : "+i);

        Picasso.with(context).load("http://placehold.it/350x150").error(R.drawable.sample).into(imageView);
    return view;
    }
}

Page Fragment :-

package abhirojpanwar.tablayout;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

;

/**
 * Created by Abhiroj on 3/3/2017.
 */

public class PageFragment extends Fragment {

    public static final String ARG_PAGE="ARG_PAGE";

    private int mPage;

    public static Fragment newInstance(int page)
    {
        Bundle args=new Bundle();
        args.putInt(ARG_PAGE,page);
        PageFragment fragment=new PageFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage=getArguments().getInt(ARG_PAGE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_page,container,false);
        GridView gridView=(GridView) view.findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(getContext()));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getContext(),"position : "+i,Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}

SimpleFragmentPagerAdapter :-

package abhirojpanwar.tablayout;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * Created by Abhiroj on 3/3/2017.
 */

public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {

    private int PAGE_COUNT=2;
    private String tabTitles[]=new String[]{"Tab 1","Tab 2"};
    Context context;


    public SimpleFragmentPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context=context;
    }

    @Override
    public Fragment getItem(int position) {
        return PageFragment.newInstance(position+1);
}

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
}

Layout Files :-

activity _main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="abhirojpanwar.tablayout.MainActivity">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"/>

</android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/viewpager"
        android:background="#ffffff"/>

</android.support.design.widget.CoordinatorLayout>

displaimage.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop">

</ImageView>

fragment_page.xml

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

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="auto_fit"
        />

</FrameLayout>

I have mentioned in ImageAdapter that there are total of 10 items. Using Logs, It also shows that it is working for rest of the items, as it is logging the respective positions. But items are never shown because scroll is blocked.Is there any key thing that I have missed?

I want to make program in java which determines the speed of internet using java ..

I have been searching the net for an answer, but I was not able to find a similair question nor answer. So here I am.

I am developing an app where a user can take a picture of a car and they will get back the car brand and possibly a model.

Currently I am using an API as a back-end to recieve the picture, the API will send the picture to a different API which can recognize the car + model. The response will be sent back to my API, I will sanitize the response and send it back to the app.

I was wondering if this would be a good structure or if I could do it like the picture below.

Current application flow: Current application flow

What I think might be better but less secure application flow:

New application flow: New application flow

My question here is, is it possible for the last application flow to be implemented so I don't have to send a picture twice, but I can just send a picture from my app directly to the API that is not mine, get the token back and get the response that way. My concern with this is that I will need to give people with an App my API_key so they can do requests to the Api that is not mine. There is the possibility of using oAuth1 but I don't know if my api key will be secure enough that way, any advice will be appreciated.

EDIT1 My sanitize function in my own back-end api is too big to implement in the App itself.

A year or two ago I saw an excellent article on OOP (Java), which showed the progression of a simple concrete logger of two or three lines of code, and a theoretical excessive thought processes by the inexperienced developer that basically said oh, I should add this in case we ever want that! By the end of the article this simple logger was a giant mess of garbage that the original developer could hardly understand himself...

Is there a common term for this type of over-complication? That article (which I dearly wish I could find again) shows the concept wonderfully for an isolated case, but I've come across entire projects where the developers had essentially programmed themselves into a knot by over-use of patterns, frameworks, libraries and other issues. In its own way, this is as bad (or even worse) than legacy VB6 spaghetti apps we inherit for replacement.

What I'm really looking for is to bring this up when interviewing. I want to know if someone is aware and conscious of how easy it is to fall into this with lack of architecture/pre-planning (and getting a fell for whether they seem to have the correct balance in place), but it's not really something I can find a lot of info on.

I am working on an iOS app where audio recording and playback should happen simultaneously but at different sampling rates.

Recording will be done through a connected USB Audio device, and playback is done through the inbuilt speaker. I am using AudioUnits for both recording and playback. AVAudioSession category is set to AVAudioSessionCategoryPlayAndRecord.

Problem is that, recording sample rate should be 96kHz whereas playback sample rate should be 8kHz and, both should run simultaneously.

Currently, whenever I use AVAudioSessionCategoryPlayAndRecord and setPreferredSampleRate to 96kHz, ultimately sampleRate property of AVAudioSession remains at 48kHz and I am loosing half of the samples while recording.

If I use AVAudioSessionCategoryRecord recording happens just fine. But I can't run the audio playback simultaneously with this category. I even tried AVAudioSessionCategoryMultiRoute with no luck, here sampleRate remains at 44.1kHz

So, my question is in iOS how to use different sample rates for recording and playback and, still run them simultaneously? Any advice or references are greatly appreciated.

Please let me know if any other details are required.

I'm developping a mobile application for ios device and i have an issue!

My app contain a search system and i want to expose my system into spotlight in IOS. I had found some informations but it's to put some selected item ! It's not dynamic ! Our database contains more than 100 000 rows. So it's not possible to put every data in spotlight search engine !

So, my question is that, can i linked Spotlight to my API to allow my users to search directely in spotlight?

Thank!

I have developed the

non renewable Subscription

in my app. i have changed the

**[NSBundle appStoreReceiptURL]** instead of transactionReceipt (for Deprecated method)

now I am receiving the receipt like below

content: {
  receipt: {
    in_app: [
      {
        is_trial_period: "false",
        original_purchase_date_pst: "2013-10-09 20:55:27 America/Los_Angeles",
        original_purchase_date_ms: "1386571707000",
        original_purchase_date: "2013-10-09 04:55:27 Etc/GMT",
        purchase_date_pst: "2013-10-09 20:55:27 America/Los_Angeles",
        purchase_date_ms: "1386571707000",
        purchase_date: "2013-10-09 04:55:27 Etc/GMT",
        original_transaction_id: "654888452251325",
        transaction_id: "654888452251325",
        product_id: "com.example.myapp.example1”,
        quantity: "1"
      }
    ],
    original_application_version: "1.0",
    original_purchase_date_pst: "2013-10-09 20:55:27 America/Los_Angeles",
    original_purchase_date_ms: "1386569706000",
    original_purchase_date: "2013-10-09 04:55:27 Etc/GMT",
    request_date_pst: "2013-10-09 20:55:27 America/Los_Angeles",
    request_date_ms: "1386571710087",
    request_date: "2013-10-09 04:55:27 Etc/GMT",
    download_id: 215425636588954,
    application_version: "1.0",
    bundle_id: "com.example.myapp”,
    adam_id: 654225311,
    receipt_type: "Sandbox"
  },
  environment: "Sandbox",
  status: 0
}

if my customer request for refund means , the receipt will contain the cancellation_date . my question is, whether the `

cancellation_date

` will be display within the

receipt or in_app

Anyone please help me to resolve my problem. Thanks advance.

I have a problem with my jsonMapping. I have the following responses:

Response 1 Response 2

The first one succesfully maps, on the second one I got the following error:

2017-03-04 11:47:24.055: Webservice.swift:90 (loadHome(user_id:)) -> Event next(Status Code: 200, Data Length: 11844)
2017-03-04 11:47:24.056: Webservice.swift:90 (loadHome(user_id:)) -> Event completed
2017-03-04 11:47:24.056: Webservice.swift:90 (loadHome(user_id:)) -> isDisposed
Binding error to UI: jsonMapping(Status Code: 200, Data Length: 11844)

Below you see the mapping classes:

https://gist.github.com/anonymous/ae0f65d4670ca6dd61008a31c3f49e52

Can anyone help me on this?


enter code here
@IBOutlet weak var textfield: UITextView!

@IBOutlet weak var label: UILabel!


var sentimentURL = "https://api.havenondemand.com/1/api/sync/analyzesentiment/v2?text=this+is+lethargic&apikey=e55bc0ff-70a5-4270-b464-aaaf3dfcc8de&text="
var sentimentResponse:NSDictionary!

func getSentiment() {
    var error:NSError?
    var encodedText = textfield.text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)


    Get.JSON(url: sentimentURL+encodedText!) {
        (response) in
        self.sentimentResponse  = response

        DispatchQueue.main.async() {

            var agggregate = self.sentimentResponse["aggregate"]!["sentiment"]! as String
            self.label.text = agggregate

        }
    }
}

in this line " var agggregate = self.sentimentResponse["aggregate"]!["sentiment"]! as String" im getting error like Type 'Any' Has no Subscript Members.please help me in sorting this problem.thankyou in advance...

I am looking to add some security to my app. My train of thought is:

I add a token, base64LoginString to my app which is sent in the header of my connection/JSON request.

Do I then need to also add this same token into my PHP scripts / pre-database connection so that before any connection to the database is made it looks to see if the token in the php connection matches that in the header of my Swift script?

I am totally new to security and really just trying to figure out where to start.

let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

let myUrl = URL(string: "https://www.mydomain.co.uk/MyApp/userLogin.php");
var request = URLRequest(url:myUrl!);

request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

request.httpMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);

So with the code above, my hope is that token is currently been sent...

1) Is this true?

2) How do I check and validate this on my server-side connection?

3) If this is not correct, what would be a better approach?

I'd like to fix my Camera View in landscape Mode. And also show an alert when user rotate view to portrait. is there any solution available ?

I'm about to add a statistic- and a shop page into my app. - My questions are; when I'm connecting a button to show the next page, should it be Show, pull or what? - I have some variables in Integers, that i'd lik to show on the statistics page. How do I do that? When I'm saying "currencyVar" or whatever on my statistics page, it doesn't recognize it.

Thanks for your patience, I hope you can help! :)

I am retrieving almondRate from Snapshot to an array cakeRatesin this class. but there is error -- use of unresolved identifier almondRate. How can i get the value of almondRate from snapshot to put in an array.
I think this may the problem of scope of a variable, help me to overcome this please!

import UIKit
import Firebase
import FirebaseStorage

class TestTableViewController: UITableViewController {

@IBOutlet var cakeTableView: UITableView!

var ref = FIRDatabase.database().reference()

var  cakeEngNames = ["almond Cake", "Jelly Cake"]
var  cakeUrNames = ["badam cake", "jeli ka cake"]
var cakeImages = [UIImage(named: "Maru")!, UIImage(named: "spices")!]
var  cakeRates = ["\(almondRate)", "45"]

override func viewDidLoad() {
        super.viewDidLoad()

    let AlmondSnap = ref.child("Karachi").child("Bakery").child("Cake").child("Almond_Cake")
    AlmondSnap.observeSingleEvent(
        of: .value, with: { (snapshot) in
            let almondRate = snapshot.value as! String
            self.cakeRates.append(almondRate)
            print("\(almondRate)")
    })
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cakeEngNames.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "TestTableViewCell", for: indexPath) as! TestTableViewCell

    cell.cakeImage.image = cakeImages[indexPath.row]
    cell.cakeEngLabs.text = cakeEngNames[indexPath.row]
    cell.cakeUrLabs.text = cakeUrNames[indexPath.row]
    cell.cakeRateLabs.text = cakeRates[indexPath.row]
    return cell
}
}

enter image description here

I am using NSURLSession for POSt And GET Request, Attaching screenshot for error Error Domain= NSURLErrorDomain Code=-1002 “”unsupported URL” UserInfo={NslocalizedDescription=unsupported url} Domain=kCFErrorDomainCFNetwork Code=-1002 “null”}}

Message from Apple Review Team as follow - We discovered one or more bugs in your app when reviewed on the iPhone running iOS 10.2.1 on Wi-Fi connected to an IPv6 network.

Specifically, an error message appears after launch. Please see the attached screenshot.

Next Steps

Please run your app on a device while connected to an IPv6 network (all apps must support IPv6) to identify any issues, then revise and resubmit your app for review.

If we misunderstood the intended behavior of your app, please reply to this message in Resolution Center to provide information on how these features were intended to work.

For new apps, uninstall all previous versions of your app from a device, then install and follow the steps to reproduce the issue. For updates, install the new version as an update to the previous version, then follow the steps to reproduce the issue.

Resources

For information about supporting IPv6 Networks, please refer to Supporting IPv6 DNS64/NAT64 Networks and About Networking.

I got this error alert from apple apple review team, the screen shot shows error from apple

In my application when a user is an online data is sent successfully but when a user is in flight mode or (no network connection) the I am trying to send data to server from local storage to server when a user is online again. but the problem is that UI is not updating from the broadcast receiver. And also when a user is online from flight mode only single name is send to server all data is not sending from SQLite to a server.

I am attaching a device image to show that image is not updating from failed to success after transferring data to the server. And show database where data4 is missing.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    EditText Name;
    RecyclerView.LayoutManager layoutManager;

    RecyclerAdapter adapter;
    ArrayList<Contact> arrayList = new ArrayList<>();

    BroadcastReceiver broadcastReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
        Name=(EditText) findViewById(R.id.name);
        layoutManager =new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        adapter = new RecyclerAdapter(arrayList);
        recyclerView.setAdapter(adapter);

        readFromLocalStorage();

        broadcastReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                readFromLocalStorage();

            }
        };


    }
    public void submitName(View view){

        String name = Name.getText().toString();
        saveToAppServer(name);
        Name.setText("");
    }


    private void readFromLocalStorage() {

        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase database = dbHelper.getReadableDatabase();

        Cursor cursor = dbHelper.readFromLocalDatabase(database);
        //String[] columns = {DbContact.NAME, DbContact.SYNC_STATUS};
       // Cursor cursor = database.query(DbContact.TABLE_NAME,
              //  columns,
               // null,
              //  null, null, null, null);

        while (cursor.moveToNext()){
            String name = cursor.getString(cursor.getColumnIndex(DbContact.NAME));
            int sync_status=cursor.getInt(cursor.getColumnIndex(DbContact.SYNC_STATUS));

            arrayList.add(new Contact(name,sync_status));

        }

        adapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToAppServer(final String name){
        if(checkNetworkConnection()){

            StringRequest stringRequest=new StringRequest(Request.Method.POST, DbContact.SERVER_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String Response = jsonObject.getString("response");

                                if(Response.equals("OK")){
                                    saveToLocalStorage(name,DbContact.SYNC_STATUS_OK);
                                }
                                else{
                                    saveToLocalStorage(name,DbContact.SYNC_STATUS_FAILED);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    saveToLocalStorage(name,DbContact.SYNC_STATUS_FAILED);


                }
            })

            {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params= new HashMap<>();
                    params.put("name", name);
                    return params;
                }
            }  ;

            VolleySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);

        }
        else{

            saveToLocalStorage(name,DbContact.SYNC_STATUS_FAILED);


        }




    }
    public boolean checkNetworkConnection(){
        ConnectivityManager connectivityManager =(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        return (networkInfo!= null && networkInfo.isConnected());
    }

    private void saveToLocalStorage(String name, int sync){

        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        dbHelper.saveToLocalDatabase(name, sync, database);
        readFromLocalStorage();
        dbHelper.close();



    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(broadcastReceiver, new IntentFilter(DbContact.UI_UPDATE_BROADCAST));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }
}

public static final String UI_UPDATE_BROADCAST ="net.simplifiedcoding.androidmysqlsync.uiupdatebroadcast";

NetworkMonitor.java

public class NetworkMonitor extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {

        if(checkNetworkConnection(context)){

            final DbHelper dbHelper=new DbHelper(context);
            final SQLiteDatabase database = dbHelper.getWritableDatabase();

            Cursor cursor=dbHelper.readFromLocalDatabase(database);

            while (cursor.moveToNext()){
                int sync_status = cursor.getInt(cursor.getColumnIndex(DbContact.SYNC_STATUS));
                if(sync_status == DbContact.SYNC_STATUS_FAILED){
                    final String Name = cursor.getString(cursor.getColumnIndex(DbContact.NAME));
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, DbContact.SERVER_URL,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String Response = jsonObject.getString("response");

                                        if(Response.equals("OK")){
                                            dbHelper.updateLocalDatabase(Name,DbContact.SYNC_STATUS_OK,database);
                                            context.sendBroadcast(new Intent(DbContact.UI_UPDATE_BROADCAST));


                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }


                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    })
                    {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String,String> params = new HashMap<>();
                            params.put("name",Name);
                            return params;
                        }
                    } ;
                    VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
                }
            }

            dbHelper.close();
        }

    }

    public boolean checkNetworkConnection(Context context){
        ConnectivityManager connectivityManager =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        return (networkInfo!= null && networkInfo.isConnected());
    }

}

One more thing its showing error in Context, dbHelper, Name that way I am adding Final to it.

I am using Navigation Drawer for Replace Fragment ,i want to show previous fragment on Backpress and problem is i Have to show snackbar on First Fragment to exit App and not to remove First Fragment and getBackStackEntryCount() show 0 count always.Here is My Code

  • Fragment Transection code

        Fragment mFragment = null;
        FragmentManager mFragmentManager = getSupportFragmentManager();
    
        switch (position){
    
            case 0://Not used Start from postion 1
                mFragment = new MainFragment().newInstance(""+position,"");
                break;
            case 1: //not used
                mFragment = MainFragment.newInstance(""+position,"");
                break;
            case 2:
                mFragment = new Download_Adr().newInstance(""+position,"");
                break;
            case 3:
                mFragment = new Adr_Status().newInstance(""+position,"");
                break;
            case 4:
                mFragment = new Update_Adr().newInstance(""+position,"");
                break;
            case 5:
                mFragment = new Update_Status().newInstance(""+position,"");
                break;
            case 6: //not useed
                mFragment = new Update_Status().newInstance(""+position,"");
                break;
            case 7: // 6th Fragment
                mFragment = new Find_Adr().newInstance(""+position,"");
                break;
            case 8:
                mFragment = new Locate_Enroll().newInstance(""+position,"");
                break;
            case 9:
                mFragment = new Locate_Enroll().newInstance(""+position,"");//same Page for Book Appointment
                break;
            case 10:
                mFragment = new FQA().newInstance(""+position,"");
                break;
            case 11:
                mFragment = new Contact_Us().newInstance(""+position,"");
                break;
    
            default:
                //mFragment = new MainFragment();
                mFragment = MainFragment.newInstance("1","");
                break;
        }
    
        if (mFragment != null)
        {
            if (position == 0 || position == 1 || position == -1)
            {
                mFragmentManager.beginTransaction().add(R.id.container, mFragment).addToBackStack("my_fragment").commit();
            }
            else
                mFragmentManager.beginTransaction().add(R.id.container, mFragment).addToBackStack("my_fragment").commit();
        }
    

onBackPressed()

 @Override
    public void onBackPressed()
    {
        if (getFragmentManager().getBackStackEntryCount() > 0)
        {
            getFragmentManager().popBackStack();
        }
        else 
        {
            super.onBackPressed();
        }
    }

After googled this topic, I know there are several ways to measure the startup time of an android app.

  1. adb logcat -b events | grep am_activity_launch_time, see this post
  2. adb logcat -s ActivityManager:I | grep Displayed
  3. use reportFullyDrawn programmatically
  4. adb shell screenrecord --bugreport /sdcard/launch.mp4, to check video frame by frame, see this post
  5. adb shell am start -w packagename/MainActivity to check the output
  6. adb logcat -s Timeline:I, to checkout "App_transition_ready" and Activity_windows_visible in the output.

What is the most precise way to measure startup time of an Android app? What are the differences among them?

I am developing an ecommerce and need your help on the designing of cache or some way so that i can retrieve millions of products to be diaplayed on ui.

Could you please suggest some reference or some help on what is the best way to design such cache. Thanks

Caps lock is always enable in win 10startup. I try to edit regedit as suggest in the web to set initial keyboard to 0. But every time I restart the computer the caps lock is on and the initial keyboard value in regedit back to 2 again. When I edit regedit, it prompt the permission dialogue so I think it's edit in the administration mode. How to let caps lock be off when the computer boot?

This question already has an answer here:

I am creating a simple way to customize table view cells with an image from your photo library. Despite it compiling without any errors, the code is not working. Is there a better way of doing this?

Here is my simple function behind saving the selected image to an Url:

private func imagePickerController(
    picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : AnyObject])
{
    var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
    let img = UIImage() //Change to be from UIPicker
    let data = UIImagePNGRepresentation(img)!
    do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let url = NSURL(string: "\(documentsPath)\(moreInfoVerse)")
        try data.write(to: url as! URL)

    } catch {
        print("Error")
    }

    dismiss(animated: true, completion: nil) //5
}

And then this is the code for loading the picture file in cell's image view:

do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let readData = try NSData(contentsOfFile: "\(documentsPath)\(officialVerseList[indexPath.row])", options: [])
        let retreivedImage = UIImage(data: readData as Data)
        cell?.imageView?.image = retreivedImage
        }
        catch {
        print("Error")
        }

I have an image which I want to post to my server with other parameters using Alamofire. I am using multipart method of Alamofire for uploading but not getting post and in console also not showing any errors.I had refer this question for implementing Uploading file with parameters using Alamofire . Here is my code:

let productImage:UIImage = itemImage.image!
let dataImage = UIImageJPEGRepresentation(productImage, 1.0)
let url = "Some URL "
let parameter = ["product_name": productName, "product_price": productPrice] 
let headers : HTTPHeaders = ["Content-Type": "application/json","Authorization" : "Some Token"]

Alamofire.upload(multipartFormData: {
            multipartFormData in

            multipartFormData.append(dataImage!, withName: "file", fileName: "file.jpg", mimeType: "image/png")
            for (key,value) in parameter {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
        }, to: url,method: .post, headers: headers, encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload,_,_):
                upload.responseJSON {[weak self] response in
                    print(response.result.value)
                }
                break
            case .failure(let encodingError):
                print("error: \(encodingError)")
                break
            }
        })

If anyone can solve my problem.Thank you.