1 . Update Recyclerview List After Deleting Row?
 

Answer :

public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> {

private static final String TAG = CartAdapter.class.getSimpleName();

private final Context context;
private List<Cart> itemsList;
private String id;

public CartAdapter(Context context, List<Cart> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout, parent, false);
    return new CartViewHolder(view);
}

@Override
public void onBindViewHolder(final CartViewHolder viewholder, final int position) {
    final Cart cart = itemsList.get(position);
    id = cart.getProductId();

    AndroidNetworking.get(Constants.PRODUCT_DETAILS_ENDPOINT + id)
            .setTag("Get Product Image")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Cart Item Image Response:\t" + response.toString());
                    String imagePath = null;
                    try {
                        JSONObject itemObject = new JSONObject(response.toString());
                        JSONObject data = itemObject.getJSONObject("data");
                        imagePath = data.getString("image");

                        Picasso.with(context)
                                .load(imagePath)
                                .placeholder(R.drawable.noimage)
                                .into(viewholder.cartItemImg);

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

                @Override
                public void onError(ANError anError) {

                }
            });

    viewholder.cartItemTitle.setText(cart.getProductTitle());
    viewholder.cartQtyTV.setText(cart.getCartQty() + "");
    viewholder.clearProductIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            removeProductRow(cart);
        }
    });
    viewholder.decreaseCartIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            decreaseProduct();
        }
    });
    viewholder.increaseCartIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            increaseProduct();
        }
    });
}

private void increaseProduct() {

}

private void decreaseProduct() {

}

public void removeProductRow(final Cart cart) {
    AndroidNetworking.get(Constants.REMOVE_PRODUCT_CART + id)
            .setTag("Delete Product From Cart")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Delete Product From Cart Response:\t" + response.toString());

                    int position = itemsList.indexOf(cart);
                    itemsList.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position, itemsList.size());
                }

                @Override
                public void onError(ANError anError) {

                }
            });
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}
}


Leave a Comment

Name  
  Email   
Message
1 . Privacy policy Issue with two permissions?
 

Answer :

The additional permissions come from Google Play Services. There's currently a bug in version 12.0.0, the services add not needed permission to your app like READ_PHONE_STATE. If you are sure you won't need this permission you can strip them out from your apk using something like that in your manifest:

<uses-permission
    android:name="android.permission.READ_PHONE_STATE"
    tools:node="remove"/>

2 . Xamarin apps confusion between Device.OnPlatform and Switch()?
 

Answer :

Yes that method is now obsolete. In order to target specific devices you have to indeed use a switch statement that gets the runtime platform as a parameter.This is an example.

  static class AppConstants
{
    public static readonly Thickness PagePadding = GetPagePadding();

    private static Thickness GetPagePadding()
    {
        double topPadding;

        switch(Device.RuntimePlatform)
        {
            case Device.iOS:
                topPadding = 20;
                break;
            default:
                topPadding = 0;
                break;
        }

        return new Thickness(5, topPadding, 5, 0);
    }
}

3 . How do I achieve this sort of swipe navigation?
 

Answer :

I'd guess that you need ViewPager:

https://developer.android.com/training/animation/screen-slide.html

Each "grid" will be separate fragment.

EDIT:

Also see this: it seems very simmilar to what you want to get: Android ViewPager with bottom dots


4 . findViewById in fragment without put in onCreateView?

Answer :

First about inflating views:

This code here:

View v;
v = inflater.inflate(R.layout.tab_match_odd, container, false);

"Inflates" the View which means that it takes xml file and just create all those objects. So after that v is a view that contains all other views defined in your xml. That is why you can use:

(TextView) v.findViewById(R.id.awayname);

Because this TextView is definec inside View.

getView() and getActivity() difference

Another thing is that your Fragment is "hosted" by Activity. It also has it's View (inflated by usage of setContentView(...) method). By this you can use Activity.findViewById() and you will be able to find views inflated in Activity's xml file (set in setContentView()). That is why:

(TextView) v.findViewById(R.id.awayname);

works, and

(TextView) getActivity().findViewById(R.id.awayname);

doesn't. Activity simply hasn't inflated the view containing R.id.awayname. So as you see: getActivity() returns you just the activity that is "hosting" fragment, and getView() returns the view that you've returned from onCreateView() method.

Why getView() produces null?

It's because you've used getView() method before onCreateView() return statement.

What to do?

To make it work it's wise to create properties inside of your Fragment/Activity like this:

public class TabMatchFragmentOdd extends Fragment { TextView Home, Away;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    View v;
    v = inflater.inflate(R.layout.tab_match_odd, container, false);
    getViews(v);
    return v;
}

private void getIncomingIntent() {
    (...)
    setContent(HomeName,AwayName);         
}

private void getViews(View v) {
    Home = (TextView) v.findViewById(R.id.homename);
    Away = (TextView) v.findViewById(R.id.awayname);      
}

private void setContent(String home, String away) {
    Home.setText(home);
    Away.setText(away);   
}

5 . How to get/return viewtype in use from adapter?
 

Answer :

If I understood your question right, you are asking whether an Adapter for RecyclerView you have in an Activity can be used for another RecyclerView in another Activity. In that case, the answer is - YES, it can be used in as many places you wish..

Don't forget, Adapter is nothing but a design pattern in programming:

Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces.

As long as you have your Adapter class accessible (not a private inner class) by your other Activity, you can reuse it with different RecyclerView and different data.



6 . Return data outside the main thread in Android Room?
 

Answer :

The problem appears to be with this code:

 public void AddProduct(final Product product){
new Thread(new Runnable() {
    @Override
    public void run() {
        db.inventory().insertOneProduct(product);
    }
});
 }

Although you have created a thread, you did not call the start method. So change it to this:

 public void AddProduct(final Product product){
new Thread(new Runnable() {
    @Override
    public void run() {
        db.inventory().insertOneProduct(product);
    }
}).start();
}

7 . Error when using Toast (Null Object Reference) [duplicate]?
 

Answer :

Your context is null you need initialize your context otherwise Pass getApplicationContext()

Toast.makeText(getApplicationContext(), "current speed:" + location.getSpeed(),
                    Toast.LENGTH_SHORT).show();

8 . Android Studio 3.1 “Run” not compiling code?
 

Answer :

1) Please edit your app configuration as below.

enter image description here

2) Here you can see your app configuration as below.

enter image description here

3) Here is missing Gradle-awake make attribute in before launch configuration. You can see here.

enter image description here

4) Please add this Gradle-awake Make attribute through this way. Click on + icon and select Gradle-awake Make as seen in this screen.

enter image description here

5) You can add this without writing any task just press OK button and task will be added and now it should look like this. Now apply changes and run your application.

enter image description here

It will solve this old apk installing issue on clean build in new android studio 3.1 issue.


9 . recyclerview not displaying all data?
 

Answer :
<LinearLayout android:layout_width="match_parent"
    android:layout_height="88dp"
    android:weightSum="1"
    xmlns:android="http://schemas.android.com/apk/res/android">

<TextView
    android:layout_gravity="center_vertical"
    android:layout_weight="0.2"
    android:layout_width="0dp"
    android:layout_height="wrap_content" />

<TextView
    android:layout_gravity="center_vertical"
    android:layout_weight="0.8"
    android:layout_width="0dp"
    android:layout_height="wrap_content" />

</LinearLayout>
This simple LinearLayout it should work You can also add other properties, but for now try it out

10 . My Notification doesn't show after closing the app?
 

Answer :

Don't call registerReceiver() from your activity, the receiver will die when you close the app. You need to declare the receiver in your Manifest. And use the receiver as an independent class not as an inner class. the AlarmManager will call your receiver using the PendingIntent data. Set your PendingIntent like this and add the following method to your Activity and call it from onCreate like so:

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

    AlarmManager alarmManager=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    Intent alarmIntent = new Intent(getApplicationContext(), YourReceiver.class);
    PendingIntent operation = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar=Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.clear();
    calendar.set(Calendar.DATE,26);
    calendar.set(Calendar.MONTH,Calendar.MARCH);
    calendar.set(Calendar.YEAR,2018);
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 52);
    calendar.set(Calendar.SECOND, 0);

    registerOneTimeAlarm(operation, calendar.getTimeInMillis());
}

private void registerOneTimeAlarm(PendingIntent alarmIntent, long when) {
    int SDK_INT = Build.VERSION.SDK_INT;
    if (SDK_INT < Build.VERSION_CODES.KITKAT) {
        alarmManager.set(AlarmManager.RTC_WAKEUP, when, alarmIntent);
    } else if (Build.VERSION_CODES.KITKAT <= SDK_INT && SDK_INT < Build.VERSION_CODES.M) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, when, alarmIntent);
    } else if (SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, when, alarmIntent);
    }
}

This method has better support for the new Android limitations.

Add the receiver to your Manifest so it can be triggered explicitly:

<receiver
        android:name=".YourReceiver"
        android:enabled="true"
        />

Put the addNotification() method in the receiver class, or start a Service that will call this method, It's not a long operation so I would just put it in the receiver.



11 . Cannot detect onNavigationItemSelected using Databind. How to get all menu item click in Navigationview?

Answer :

Please check if you have done this.You need to implement listener otherwise it won't work.Please let me know if the solution work

binding = DataBindingUtil.setContentView(this, R.layout.activity_dashboard);
binding.navView.setNavigationItemSelectedListener(this);

and remove this line from XML:

app:navigationItemSelectedListener="@{navigationItemSelectedListener::onNavigationItemSelected}"

12 . Android studio 3.1 run command does not rebuild the APK [duplicate]?
 

Answer :

Go to Run -> Edit configurations. And then make sure you have Gradle-aware Make option like below screenshot.

enter image description here

If not then click + and select from the options.


13 . Uninstall APP using its APK?
 

Answer :

If you want to uninstall app then it must be installed right? you can get all installed app and it's package names as well as other info like icon,path,launcher activity etc... and ask user to select app they want to uninstall that way you'll know the package name of that app.

you can get list of installed app like this

final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) {
    Log.d(TAG, "Installed package :" + packageInfo.packageName);
    Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
    Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); 
}

there is no way to uninstall app from APK

EDIT

Check out this method from the PackageManager class:

public PackageInfo getPackageArchiveInfo(String archiveFilePath, int flags)

useful to read package archives.not sure if this is what you want.


14 . Extracting Values Not Working JSON file?
 

Answer :

First the bug. It must be NullPointerException.

    while (line !=null)

it will run until line = null. Then this line will give you the exception.

    new JSONObject(line);

and you shoud get the graphql first.

so the solution should look like this.

if(line != null) {
    JSONObject jo = new JSONObject(line);
    JSONObject graphql = jo.getJSONObject("graphql");
    JSONObject user = graphql.getJSONObject("user");
    name = user.getString("full_name");

15 . Intent.getIntExtra() is giving unexpected results?

Answer :

I am doing same thing and I am getting proper output:

ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        Log.v(TAG," Notification id:" + model.getNotificationIdForLocalDB());

        Intent intent1 = new Intent(context, AlarmReceiver.class);
        intent1.putExtra("notification_id", model.getNotificationIdForLocalDB());
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, model.getNotificationIdForLocalDB(), intent1, PendingIntent.FLAG_UPDATE_CURRENT);

And at BroadcastReceiver end :

if(intent != null){
            if(intent.getExtras() != null){
                notificationId = intent.getExtras().getInt("notification_id",0);
            }
        }

try to change Pending intent flag 0 to PendingIntent.FLAG_UPDATE_CURRENT