Friday 18 November 2016

Retrofit File Upload:

Config class:

public class RetroConfig {

    public static Retrofit retrofit(){

        OkHttpClient client = new OkHttpClient();
        client.retryOnConnectionFailure();
        client.cache();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://bestvote.in/privilege/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        return retrofit;
    }
}

Create Api Interface:

import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONObject;

import okhttp3.ResponseBody;
import retrofit.Call;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.Multipart;
import retrofit.http.POST;
import retrofit.http.Part;
import retrofit.http.Path;
import retrofit.http.Query;
public interface ApiInterface {

    @Multipart
    @POST("insertpost.php")
    Call<CommonResponse> submitForm(@Part("description") RequestBody desc, @Part("audio\"; filename=\".mp3\" ") RequestBody audio,
                              @Part("image\"; filename=\".jpg\" ") RequestBody photo,
                              @Part("late") RequestBody lat, @Part("long") RequestBody lon);

    @GET("allpost.php")
    Call<SellerResponse> getSellerAds();
}

Call Api Post method:

import retrofit.Call;
import retrofit.Callback;
import retrofit.Retrofit;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

private void submitForm() {
        String desc = details.getText().toString();

        if (!desc.equals("") && imagePath!=null && audioPath!=null) {
            RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
            RequestBody latBody = RequestBody.create(MediaType.parse("text/plain"), latFinal);
            RequestBody lonBody = RequestBody.create(MediaType.parse("text/plain"), lngFinal);
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(imagePath));
            RequestBody audioBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(audioPath));
            //RequestBody videoBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(videoPath));

            final ProgressDialog dialog = new ProgressDialog(SellerActivity.this);
            dialog.setMessage("Uploading...");
            dialog.setCancelable(false);
            dialog.show();

            Call<CommonResponse> call = RetroConfig.client().submitForm(descBody, audioBody, imageBody, latBody, lonBody);
            call.enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(retrofit.Response<CommonResponse> response, Retrofit retrofit) {
                    dialog.cancel();
                    if (response.body() != null) {
                        CommonResponse response1 = response.body();
                        if(response1.getResponse().equals("success")){
                            Toast.makeText(SellerActivity.this, "Upload Ads successfully..", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(SellerActivity.this, SellerAds.class));
                            finish();
                        }
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.e("submitError", t.getLocalizedMessage());
                    dialog.cancel();
                }
            });
        } else {
            Utils.showDialog(SellerActivity.this, "Please select All files");
        }
    }   

CallGet Method:

RetroConfig.client().getSellerAds().enqueue(new Callback<SellerResponse>() {
            @Override
            public void onResponse(Response<SellerResponse> response, Retrofit retrofit) {
                SellerResponse sr = response.body();
                String status = sr.getResponse();
                if(status.equals("success")){
                    List<SAds> sAdses = sr.getSellerAds();
                    rv.setAdapter(new SellerAdsAdapter(SellerAds.this, sAdses));
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.e("error", t.getLocalizedMessage());
            }
        });

Thursday 10 November 2016


Dynamic ViewPager:-

in Activity :


public class MainActivity extends AppCompatActivity {

    ViewPager mPager;

    int numPages = 0;

    String[] mImageArray;

    int addNext = 0;
    EndLessAdapter adapter;

    ArrayList<String> arrayList;

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

        arrayList = new ArrayList<>();

        String number = getIntent().getStringExtra("number");
        numPages = Integer.parseInt(number);

        mImageArray = new String[numPages];

        addNext = numPages;

        for (int i = 0; i < numPages; i++) {
            mImageArray[i] = "Click " + String.valueOf(i + 1);
            arrayList.add("Click " + String.valueOf(i + 1));
        }

        mPager = (ViewPager) findViewById(R.id.frame);
        mPager.setOffscreenPageLimit(0);
        adapter = new EndLessAdapter(this, arrayList);
        mPager.setAdapter(adapter);
    }

    public void addNewpage() {
        arrayList.add("Click " + String.valueOf(addNext + 1));
        adapter.notifyDataSetChanged();
        addNext = addNext + 1;
    }

    public class EndLessAdapter extends PagerAdapter {

        FragmentActivity activity;
        ArrayList<String> stringArrayList1;
        // String imageArray[];
        private int pos = 0;

        public EndLessAdapter(FragmentActivity act, ArrayList<String> stringArrayList) {
            stringArrayList1 = stringArrayList;
            activity = act;
        }

        public int getCount() {
            return Integer.MAX_VALUE;
            //return imageArray.length;
        }

        public Object instantiateItem(View collection, int position) {

            Button mwebView = new Button(activity);
            ((ViewPager) collection).addView(mwebView, 0);
            // mwebView.setScaleType(ImageView.ScaleType.FIT_XY);
            mwebView.setText(stringArrayList1.get(pos));

            mwebView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    addNewpage();
                }
            });

            if (pos >= stringArrayList1.size() - 1)
                pos = 0;
            else
                ++pos;

            return mwebView;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == ((View) arg1);
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

    }
}

in XML file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.com.dynamicviewpager_android.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true" >
    </android.support.v4.view.ViewPager>
</RelativeLayout>

BackStack in Fragments:-

Create Interface class:

public interface OnBackListner {
    void back();
}

In Activity:

public class HomeActivity extends AppCompatActivity{

    OnBackListner onBackListner;

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

    @Override
    public void onBackPressed() {
            if (onBackListner != null) {
                onBackListner.back();
            } else {
                finish();
            }       
    }

    public void setOnBackPressedListener(OnBackListner onBackPressedListener) {
        this.onBackListner = onBackPressedListener;
    }

}

In 1st Fragment :

((HomeActivity) getActivity()).setOnBackPressedListener(new OnBackListner() {
            @Override
            public void back() {
                //startActivity(new Intent(getActivity(), MainActivity.class));
                CommonUtils.hideKeyboard(getActivity());
                getActivity().finish();
            }

        });

2nd Fragment:

((HomeActivity) getActivity()).setOnBackPressedListener(new OnBackListner() {
            @Override
            public void back() {
                //startActivity(new Intent(getActivity(), MainActivity.class));
                CommonUtils.hideKeyboard(getActivity());
                getActivity().getSupportFragmentManager().popBackStackImmediate();
            }

        });

Fragment Transaction:-

Simple Fragment Transaction:

Fragment 1:

Fragment fragment = new EditProfileFragment();

Bundle bundle = new Bundle();
bundle.putString("myrideRideId", "1035");

fragment.setArguments(bundle);

getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, 
                         R.anim.enter_from_left,  R.anim.exit_to_right)
                        .replace(R.id.frame_container, fragment)
                        .addToBackStack(null)
                        .commit();

Fragment 2:

getActivity().getSupportFragmentManager().popBackStackImmediate();

Simple Fragment Add:

getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.frame_container, fragment)
                    .commit();


Tuesday 25 October 2016


Broadcast in GCM:

onMessageReceived method:

Intent intent = new Intent(MessageReceiver.name);
sendBroadcast(intent);

Create class Reciever:

public class MessageReceiver extends BroadcastReceiver{
    public static String name = "com.app.privilege.receiver.MESSAGE";
    @Override    public void onReceive(Context context, Intent intent) {

    }
}

In MainActivity:

Above Oncreate
MessageReceiver receiver = new MessageReceiver() {
    @Override    public void onReceive(Context context, Intent intent) {
        displayData();
    }
};

In Oncreate:

registerReceiver(receiver, new IntentFilter("com.app.privilege.receiver.MESSAGE"));

public void displayData() {
    adapter.notifyDataSetChanged();
    recyclerView.invalidate();
}


On Destroy:
@Overrideprotected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}

In Manifest:

<receiver    android:name=".receiver.MessageReceiver"    android:enabled="true">
    <intent-filter>
        <action android:name="com.app.privilege.receiver.MESSAGE" />
    </intent-filter>
</receiver>






SuffleList Example

MainActivity:


public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private GridLayoutManager mLayoutManager;


    private ArrayList<String> text1 = new ArrayList<String>();
    private ArrayList<String> text2 = new ArrayList<String>();

    private ArrayList<Integer> spos = new ArrayList<Integer>();
    private ArrayList<Integer> sposnew = new ArrayList<Integer>();
    private ArrayList<Integer> sposnewselected = new ArrayList<Integer>();
    private Button b1, b2;
    TextView txt1;
    int sposp;
    int pos;


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

        String count = getIntent().getStringExtra("count");
        if (!TextUtils.isEmpty(count)) {
            for (int i = 0; i < Integer.parseInt(count); i++) {
                text1.add("A " + String.valueOf(i));
                text2.add("a " + String.valueOf(i));
                spos.add(i);
            }
        } else {
            for (int i = 0; i < 20; i++) {
                text1.add("A " + String.valueOf(i));
                text2.add("a " + String.valueOf(i));
                spos.add(i);
            }
        }

        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        txt1 = (TextView) findViewById(R.id.text1);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet(), MainActivity.this);
        mRecyclerView.setAdapter(mAdapter);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Collections.shuffle(spos);
                Toast.makeText(MainActivity.this, String.valueOf(spos.get(0)), Toast.LENGTH_SHORT).show();
            }
        });
        b2.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                getFirstPos();
            }
        });

        suffleList();
    }

    @Override    protected void onResume() {
        super.onResume();
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();
        for (int index = 0; index < text1.size(); index++) {
            DataObject obj = new DataObject(text1.get(index).toString(), text2.get(index).toString(), spos.get(index));
            results.add(index, obj);
        }
        return results;
    }


    public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
        private String LOG_TAG = "MyRecyclerViewAdapter";
        private ArrayList<DataObject> mDataset;
        Context context;

        public class DataObjectHolder extends RecyclerView.ViewHolder {
            TextView label;
            TextView dateTime;
            LinearLayout layout_my;

            public DataObjectHolder(View itemView) {
                super(itemView);
                label = (TextView) itemView.findViewById(R.id.textView);
                dateTime = (TextView) itemView.findViewById(R.id.textView2);
                layout_my = (LinearLayout) itemView.findViewById(R.id.layout_my);
            }
        }

        public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset, Context context) {
            mDataset = myDataset;
            this.context = context;
        }

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

        @Override        public void onBindViewHolder(final DataObjectHolder holder, final int position) {
            final DataObject dataObject = mDataset.get(position);
            holder.label.setText(mDataset.get(position).getmText1());
            holder.dateTime.setText(mDataset.get(position).getmText2());

            if (sposnewselected.size() > 0) {
                if (sposnewselected.contains(position)) {
                    holder.layout_my.setBackgroundResource(R.color.colorPrimaryDark);
                }
            }

            if (sposnew.size() > 0) {
                if (position == sposnew.get(0)) {
                    holder.layout_my.setBackgroundResource(R.color.colorAccent);
                }
            }

            holder.layout_my.setOnClickListener(new View.OnClickListener() {
                @Override                public void onClick(View view) {
                    if (sposnew.size() > 0) {

                        if (position == sposnew.get(0)) {
                            holder.layout_my.setBackgroundResource(R.color.colorAccent);
                            getFirstPos();
                            notifyDataSetChanged();
                        }
                    }
                }
            });

        }

        @Override        public int getItemCount() {
            return mDataset.size();
        }

        public int getItemViewType(int position) {
            return position;
        }

    }

    String listString = "";
    String listString1 = "";

    public void suffleList() {
        Collections.shuffle(spos);
        for (int str : spos) {
            sposnew.add(str);
            listString += String.valueOf(str) + "\t";
        }
        txt1.setText(listString);
    }

    public void getFirstPos() {
        if (sposnew.size() > 0) {
            sposnewselected.add(sposnew.get(0));
            sposnew.remove(0);
            for (int str : sposnew) {
                listString1 += String.valueOf(str) + "\t ";
            }
            Log.e("new str", listString1);
        }
    }

    @Override    public void onBackPressed() {
        finish();
    }
}


ModelClass:

public class DataObject {

private String mText1;

private String mText2;

private int spos;

public DataObject(String mText1, String mText2, int spos) {

this.mText1 = mText1;

this.mText2 = mText2;

this.spos = spos;

}

public String getmText1() {

return mText1;

}

public void setmText1(String mText1) {

this.mText1 = mText1;

}

public String getmText2() {

return mText2;

}

public void setmText2(String mText2) {

this.mText2 = mText2;

}

public int getSpos() {

return spos;

}

public void setSpos(int spos) {

this.spos = spos;

}

}

Retrofit 2.1:

Add gradle in your app.gradle file

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

Create interface

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Api {

    @FormUrlEncoded    @POST("driver_login")
    Call<DriverLoginResponse> driverLogin(@Field("email") String email,
                                          @Field("password") String password,
                                          @Field("deviceId") String deviceId,
                                          @Field("deviceType") String deviceType);

}

Create Time class for call api:

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetroConfig {

    public static Api client() {
 
        OkHttpClient.Builder b = new OkHttpClient.Builder();
        b.readTimeout(200, TimeUnit.SECONDS);
        b.writeTimeout(600, TimeUnit.SECONDS);
        OkHttpClient client = b.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        Api apiInterface = retrofit.create(Api.class);
        return apiInterface;


    }



MainActivity.class:

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

final ProgressDialog dialog = new ProgressDialog(OtpActivity.this);
dialog.setMessage("please wait...");
dialog.setCancelable(false);
dialog.show();

Call<ResponseBody> responseCall = RetroConfig.client().verifyOtp(driver_id, otp);
responseCall.enqueue(new Callback<ResponseBody>() {
    @Override    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        dialog.cancel();
        if (response.body() != null) {
            try {
                String result = response.body().string();

                JSONObject jsonObj = new JSONObject(result);

                String sres = jsonObj.getString("responce");

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

        }
    }

    @Override    public void onFailure(Call<ResponseBody> call, Throwable t) {
        dialog.cancel();
        Log.e("error", t.getLocalizedMessage());
    }
});