Upload a file along with other string parameters in android - android

I have to upload a file and has three more parameters which is string.The file can be image or zip.How is it possible with volley to upload a file and submit string parameters along with it when button is clicked?
I have also tried this link-https://www.simplifiedcoding.net/upload-pdf-file-server-android/
Please help me.Thanks!!
My code is:
public class Tab1Fragment extends Fragment implements
AdapterView.OnItemSelectedListener {
EditText subj,desx;
private ImageView mAvatarImage;
Button choosefile,select,submt;
String uid, type;
String MY_PREFS_NAME = "value";
private int PICK_PDF_REQUEST = 1;
TextView filetext;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
String uploadId;
//Uri to store the image uri
private Uri filePath;
Spinner spinner,spinner2;
public Tab1Fragment() {
// Required empty public constructor
}
public static Tab1Fragment newInstance() {
Tab1Fragment fragment = new Tab1Fragment();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_tab1, container,
false);
subj=(EditText)rootview.findViewById(R.id.subj);
choosefile=(Button)rootview.findViewById(R.id.choosefile);
select=(Button)rootview.findViewById(R.id.select);
submt=(Button)rootview.findViewById(R.id.submt);
filetext=(TextView)rootview.findViewById(R.id.filetext);
mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
desx=(EditText)rootview.findViewById(R.id.desx);
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveProfileAccount();
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
choosefile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadMultipart();
}
});
requestStoragePermission();
SharedPreferences prefs =
this.getActivity().getSharedPreferences(MY_PREFS_NAME,
Context.MODE_PRIVATE);
uid = prefs.getString("uid", null);
spinner = (Spinner)rootview.findViewById(R.id.spinner);
spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> deparment= new ArrayList<String>();
deparment.add("Support");
deparment.add("Project");
deparment.add("Payment");
deparment.add("Service");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
List<String> priority= new ArrayList<String>();
priority.add("low");
priority.add("Medium");
priority.add("High");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);
// Drop down layout style - list view with radio button
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter2);
return rootview;
}
private void saveProfileAccount() {
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject b = new JSONObject(resultResponse);
int status = b.getInt("status");
String data = b.getString("message");
Log.d("Response", data);
if (status ==100) {
/* Intent intent = new Intent(getActivity(),Skills.class);
startActivity(intent);*/
Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);
params.put("department", spinner.getSelectedItem().toString());
params.put("priority",
spinner2.getSelectedItem().toString().trim());
params.put("subject", subj.getText().toString().trim());
params.put("description",desx.getText().toString().trim());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);
}

try this
public void fileUploadFunction() {
// Getting file path using Filepath class.
Pdfuri = FilePath.getPath(this, uri);
Log.d("Pdfuri", Pdfuri);
// If file path object is null then showing toast message to move file into internal storage.
if (Pdfuri == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
}
// If file path is not null then PDF uploading file process will starts.
else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, AppConstants.URL)
.addFileToUpload(Pdfuri, "pdf")
.addParameter("course", course.trim())
.addParameter("course_id", c_id.trim())
.addParameter("stream", stream.trim())
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this,
exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}

VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Read response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Add post values here
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// Add you file here
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
You can use multipart for this. Here is a sample code

Related

How to call more than one api in single activity by making separate class for all volley operations

I have created a separate class in which I have defined all about volley and in another activity, I have directly pass URL, CONTEXT and Get Response...
but in my NavDrawerActivity.java how do I call the subCategoryJSON(); method without writing my volley code again as I have done with mainCategoryJSON(); method in which I just simply pass the URL, method type.
Also is this a correct approach I am doing or there need to be some modification in the code, what I want is that wherever I am using API in my project and using volley for it, I don't have to write code again and again just simply pass the URL,method type
VolleyResponseListener.java
public interface VolleyResponseListener {
void onResponse(String response, String tag);
void onError(VolleyError error, String tag);
}
CustomStringRequestVolley.java
public class CustomStringRequestVolley {
private String url;
private String tag;
Context ctx;
private VolleyResponseListener volleyResponseListener;
public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
this.url = url;
this.tag = tag;
this.ctx=ctx;
this.volleyResponseListener = volleyResponseListener;
sendRequest();
}
private void sendRequest() {
final ProgressDialog pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Loading ...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("catresponse", "response " + response);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
volleyResponseListener.onResponse(response, tag);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);
}
}
NavDrawerActivity.java
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainCategoryJSON();
subCategoryJSON();
}
private void mainCategoryJSON() {
CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);
}
#Override
public void onResponse(String response, String tag) {
switch (tag) {
case "TAG1":
try {
Log.i("Responseeeeeezaq :", response.toString() + " " + tag);
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
CategoryModelClass categoryModelClass = new CategoryModelClass();
categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
categoryArrayList.add(categoryModelClass);
Log.d("zpuyi", String.valueOf(categoryArrayList));
}
categoryAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
VolleyLog.e("Error: ", error.getMessage());
}
private void subCategoryJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("subcategoryJsonResponse", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
You have written the answer correctly but you are not implementing the written custom volley class code in the activity class.
First Define the interface class for the Volley as below,
Now implement the volley interface in the java class where you have written the custom volley class as below:
CustomStringRequestVolley.java
public class CustomStringRequestVolley implements volleyCallback {
public Context context;
public CustomStringRequestVolley(Context context) {
this.context = context;
}
public interface volleyCallback {
void onSuccess(String result);
void onError(String error);
}
public void callGetServer(String URL, final
volleyCallback callback){
if (!checkInternetConnection(context)) {
showNoInternetDialogue(context);
return;
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}, error -> {
if (error.networkResponse == null){
if (error.getClass().equals(TimeoutError.class)){
Toast.makeText(context, "Timeout.Please try again",
Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NoConnectionError.class)){
Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NetworkError.class)) {
Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ParseError.class)){
Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ServerError.class)){
Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
}
else {
parseVolleyError(error);
}
}
}
) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
//setting up the retry policy for slower connections
int socketTimeout = 120000;//120000 milli seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Now use this Custom volley class in every activity you required. It reduces you
boilerplate code
NavDrawerActivity.java
CustomStringRequestVolley customStringRequestVolley;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point_navigation);
customStringRequestVolley = new CustomStringRequestVolley(this);
}
private void subCategoryJSON() {
customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String error) {
//show error code
}
});
}
Let me know after you try this #Abhishek

I try to login but it does not run the whole query

When I put something wrong, I receive everything in onResponse but it does not go for the function resultado() and when I put all the data well, it goes to the function resultaod() but only until the time to assign the values ​​to usuario and from the toast it is not executed.
Login Activity
public class LoginActivity extends AppCompatActivity {
private RelativeLayout parentLayout;
private EditText txtUsuario, txtContraseña;
private TextView txtVersion;
private CheckBox chxRecordar;
private Button btnEntrar;
private SharedPreferences myPreferences;
private Usuario usuario;
private String codes, status, token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
iniciarComponentes();
btnEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verificarInicio();
}
});
}
private void iniciarComponentes() {
parentLayout = findViewById(R.id.parent_layout);
txtUsuario = findViewById(R.id.txt_usuario);
txtContraseña = findViewById(R.id.txt_password);
chxRecordar = findViewById(R.id.chx_recordar);
btnEntrar = findViewById(R.id.btn_entrar);
txtVersion = findViewById(R.id.txt_version);
txtVersion.setText("Version " + BuildConfig.VERSION_NAME);
myPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
private void verificarInicio() {
String url = Common.BASE_URL + "usuario";
if (validarSesion()) {
Log.d("verificarInicio: ", url);
final String usuario = txtUsuario.getText().toString();
final String contraseña = txtContraseña.getText().toString();
final android.app.AlertDialog dialog = new SpotsDialog.Builder().setContext(this).setMessage("Cargando...").setCancelable(false).build();
dialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar.make(parentLayout, error.getMessage(), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> parametros = new HashMap<>();
parametros.put("dni", usuario);
parametros.put("password", contraseña);
return parametros;
}
};
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<String>() {
#Override
public void onRequestFinished(Request<String> request) {
if (dialog.isShowing())
dialog.dismiss();
}
});
}
}
private void resultado(String codes, String status, JSONObject jsonObject, String token) throws JSONException {
if (codes.equals("100")) {
JSONArray array = jsonObject.getJSONArray("result");
JSONObject dato = array.getJSONObject(0);
usuario = new Usuario(dato.getString("NombreCompleto"),
dato.getString("estado"),
dato.getString("foto"),
dato.getString("nombre_Aso"),
dato.getString("nombre_Red"),
dato.getString("sexo_Pro"),
dato.getInt("campana"));
Toast.makeText(LoginActivity.this, status, Toast.LENGTH_SHORT).show();
Common.USUARIO_DNI = txtUsuario.getText().toString();
guardarUsuario(token);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(Common.USUARIO, usuario);
startActivity(intent);
finish();
} else if (codes.equals("200")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
} else if (codes.equals("203")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
}
}
private boolean validarSesion() {
if (TextUtils.isEmpty(txtUsuario.getText()) || TextUtils.isEmpty(txtContraseña.getText())) {
Snackbar.make(parentLayout, "Ingrese su usuario y contraseña", Snackbar.LENGTH_SHORT).show();
return false;
}
return true;
}
private void guardarUsuario(String token) {
SharedPreferences.Editor myEditor = myPreferences.edit();
if (chxRecordar.isChecked()) {
if (!myPreferences.contains(Common.USUARIO)) {
myEditor.putString(Common.USUARIO, txtUsuario.getText().toString());
myEditor.putString(Common.CONTRASEÑA, txtContraseña.getText().toString());
myEditor.putBoolean(Common.CHECK_ESTADO, chxRecordar.isChecked());
myEditor.putString(Common.TOKEN, token);
myEditor.apply();
if (Common.USUARIO_DNI.isEmpty()) {
Common.USUARIO_DNI = myPreferences.getString(Common.USUARIO, "");
}
}
} else {
myEditor.clear();
myEditor.commit();
}
}
}
The whole code is not executed, only a part, I do not know why, I would be grateful if you helped me
check that recibe in a catch, the problem is when get the string for the jsonObject
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}

I need to display data on top of a RecyclerView after refreshing in reverse order

Recycle view load list and reached at top by mList.add(0,actor) but i want to reverse the list.
also i chnaged my code like this,
mLayoutManager.setReverseLayout(true);
mList.add(0,actor);
Here is my recycleview info, This is my recyclview api code InfoJson() here:
public class GatekeeperInfoActivity extends BaseActivity implements View.OnClickListener , MyComplaintListner {
private RecyclerView mRecyclerView;
private GateInfoAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<GateInfoPojo> mList;
Context ctx;
String visitor_id,id,cid;
M_Shared_Pref m_shared_pref;
ImageView back_button, img;
private MyDialog dialog;
TextView complaint,subject,msg,from_name_txt;
ImageView attach;
String from_id,from_name,from_mobile;
String id_rwa,new_id;
public static final int DISMISS_TIMEOUT = 2000;
LinearLayout ll_no_data;
int limit =0;
int limit_refresh;
static int nums;
private appconfig.EndlessRecyclerOnScrollListener scrollListener;
LinearLayoutManager linearLayoutManager;
public int overallXScrol = 0;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rwa_view_info);
ctx = GatekeeperInfoActivity.this;
dialog = new MyDialog(this);
m_shared_pref = new M_Shared_Pref(GatekeeperInfoActivity.this);
visitor_id = m_shared_pref.getPrefranceStringValue(App_Info.Visitor_ID);
id = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id);
cid = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id_cid);
Bundle bundle = this.getIntent().getExtras();
from_id = bundle.getString("id");
from_name = bundle.getString("name");
from_mobile = bundle.getString("mobile");
id_rwa = getIntent().getStringExtra("id_rwa");
if (from_id != null && !from_id.isEmpty() && !from_id.equals("null"))
{ new_id = from_id; }
else{ new_id = id_rwa; }
System.out.println("check:check"+from_id+":"+id_rwa);
///// using this new_id
mList = new ArrayList<GateInfoPojo>();
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GateInfoAdapter(mList, ctx);
ll_no_data = findViewById(R.id.ll_no_data);
mAdapter.setMyClickListener(this);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
});*/
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(-1)) {
// Toast.makeText(GatekeeperInfoActivity.this, "Last", Toast.LENGTH_LONG).show();
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
}
});
img = findViewById(R.id.pic);
from_name_txt = findViewById(R.id.from_name_txt);
attach = findViewById(R.id.attach);
msg = findViewById(R.id.msg);
complaint = findViewById(R.id.complaint);
subject = findViewById(R.id.subject);
back_button = findViewById(R.id.back_button);
back_button.setOnClickListener(this);
attach.setOnClickListener(this);
if(NetWorkCheck.checkConnection(GatekeeperInfoActivity.this)){
mList.clear();
InfoJson();
}
else{
TastyToast.makeText(getApplicationContext(), "Internet connection is disable", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back_button:
finish();
break;
case R.id.attach:
if(msg.getText().toString().length()>0){
submitReply(msg.getText().toString(),new_id);
}
else{
TastyToast.makeText(getApplicationContext(), "Enter Message", TastyToast.LENGTH_LONG, TastyToast.INFO);
}
break;
}
}
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public void onItemClick(View v, Object bean, String feed, String rating,String comp_spinner) {
String complaint_id = ((GateInfoPojo) bean).getId();
// submitComplaintInfo(complaint_id,feed,rating,comp_spinner);
}
#Override
public void onItemClickActivity(View v, Object bean) {
String complaint_id = ((GateInfoPojo) bean).getId();
}
public void submitReply(final String msg1,final String new_id) {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"ChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
if (error.equals("true"))
{
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
msg.setText("");
InfoJson();
mList.clear();
}
else
{
TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("fid", id);
params.put("empid", new_id);
params.put("usertype", "FlatUser");
params.put("message", msg1);
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
}
But this is not working its add to top but not reverse the api data bottom to top.
Any help would be appreciated.
You can reverse the array list by -
Collections.reverse(mList);
After that setAdapter() or notifyDataSetChanged() according to your requirement.
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
}
Collections.reverse(mList);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
// mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
Try adding the following code, both of them need to be true.
mLayoutManager.setStackFromEnd(true);
mLayoutManager.setReverseLayout(true);
From OnCreate() remove your setadapter as your list doesn't have data yet.
and in your onResponse() reverse your listdata before setting it
Collections.reverse(mList);
mAdapter = new GateInfoAdapter(mList, ctx);
mRecyclerView.setAdapter(mAdapter);

Can we change the backgroud color of Linearlayout of Fragmet A from another Fragment B ? without getting error

I want change the background color of of LinearLayout of Fragment A from Fragment B .These fragments are in same viewpager in sliding tabs.
The data of both fragment are dynamically changed from server.Here I have to click a textview of Fragment B then its linearlayout's color be changed manually(POST method) but due to net slow the background color of Fragment A (Because the textview of Fragment A is already selected so its color is already set.) is not removed from LinearLayout(GET method). But after sometime it will disappear .
So I want to set color manually till color is to be loaded. To make good user interface while clicking on textview for selection package.
MinPackageFragment
public class MinPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private View mView;
private TextView nepal_minimum_package_price, nepal_minimum_package_plan;
private LinearLayout nepal_minimum_package_linearlayout;
private String GET_NEPAL_MIN_PACKAGE_URL;
private String CHECK_CURRENT_PACKAGE_URL;
private WebView webview;
private String minPackagePrice;
private String minPackageItem;
private int THIS_ID;
private String CHOOSE_PACKAGE;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_min_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1001;
GET_NEPAL_MIN_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1001?token=" + token;
webview = (WebView) mView.findViewById(R.id.minimumNepaliListWebView);
webview.getSettings().setJavaScriptEnabled(true);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_minimum_package_price = mView.findViewById(R.id.nepal_minimum_package_price);
nepal_minimum_package_plan = mView.findViewById(R.id.nepal_minimum_package_plan);
nepal_minimum_package_linearlayout = mView.findViewById(R.id.nepal_minimum_package_linearlayout);
nepal_minimum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I want change here the background color of linearlayout of another fragment but getting error
showDialog();
choosePackage();
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setContentFromServer();
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
String avgprice = pref123.getString("mineprice", minPackagePrice);
String avgitems = pref123.getString("minitems", minPackageItem);
nepal_minimum_package_price.setText(avgprice);
webview.loadData(avgitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return mView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
Log.v("mydata1", data + "");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
hideDialog();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setContentFromServer() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_MIN_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = silver.getString("name");
minPackagePrice = silver.getString("price");
minPackageItem = silver.getString("includes");
if (getActivity() != null) {
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref123.edit();
editor.putString("mineprice", minPackagePrice);
editor.putString("minitems", minPackageItem);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
MaxPackageFragment
public class MaxPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private WebView maximumNepaliListWebView;
private View maxView;
private TextView nepal_maximum_package_plan, nepal_maximum_package_price;
private String GET_NEPAL_PACKAGE_URL;
private String maxPackageprice;
private String maxPackageitems;
private String CHECK_CURRENT_PACKAGE_URL;
private LinearLayout nepal_maximum_package_linearlayout;
private String CHOOSE_PACKAGE;
private int THIS_ID;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
maxView = inflater.inflate(R.layout.fragment_max_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1003;
GET_NEPAL_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1003?token=" + token;
nepal_maximum_package_linearlayout = maxView.findViewById(R.id.nepal_maximum_package_linearlayout);
maximumNepaliListWebView = maxView.findViewById(R.id.maximumNepaliListWebView);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_maximum_package_plan = maxView.findViewById(R.id.nepal_maximum_package_plan);
nepal_maximum_package_price = maxView.findViewById(R.id.nepal_maximum_package_price);
nepal_maximum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
// I want change here the background color of linearlayout of another fragment but getting error
choosePackage();
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setItemToLayout();
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
String maxprice = pref1.getString("maxprice", maxPackageprice);
String maxitems = pref1.getString("maxitems", maxPackageitems);
nepal_maximum_package_price.setText(maxprice);
maximumNepaliListWebView.loadData(maxitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return maxView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1003) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
hideDialog();
}
}
}
else {
JSONArray errordata = responceData.getJSONArray("errors");
String errormessage = errordata.getJSONObject(0).getString("message");
Toast.makeText(getActivity(), "" + errormessage, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setItemToLayout() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
Log.v("responceData", "onResponse: " + responceData);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = platinum.getString("name");
maxPackageprice = platinum.getString("price");
maxPackageitems = platinum.getString("includes");
if (getActivity() != null) {
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("maxprice", maxPackageprice);
editor.putString("maxitems", maxPackageitems);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID ==1003){
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
There are three fragments in same viewpager of fragment,within three tabs.
If your fragment is in same Activity, You can use the FragmentManager. findFragmentById(int id) which return by invoke Fragment.getFragmentManager() method to retrieve the reference of another fragment
then invoke the method to change the background color

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

Categories

Resources