so im tring to check data before i press toggle button but i cannot get the right logic to do the process
so i think i should do if checked look at the database set the background resource then i do the if pressed but i doesnt work
like it doesnt even change the backgroundResource
i tried to change buttonView to myViewholder.btn.setBackgroundResource but it doesnt work neither
toggle button
myViewHolder.btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
if (myViewHolder.btn.isChecked()) {
sessionManager = new SessionManager(zContext);
final HashMap<String, String> user = sessionManager.getUserDetail();
final String user_id2 = user.get(USER_ID);
String user_id = data.getUser_id();
final String post_id = data.getPost_id();
String URL = HOST + "/likes_table.php";
sessionManager = new SessionManager(zContext);
AndroidNetworking.get("http://10.0.2.2/Final/gettinglike.php")
.setPriority(Priority.LOW)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse: " + response);
{
try {
for (int i = 0; i < response.length(); i++) {
final JSONObject data = response.getJSONObject(i);
if (data.getString("post_id").equals(post_id)) {
String like_id = data.getString("like_id");
String user_id = data.getString("user_id").trim();
String post_id = data.getString("post_id");
if (user_id.equals(user_id2)){
myViewHolder.btn.isChecked();
buttonView.setBackgroundResource(ic_star_black_24dp_checked);
}
else{
buttonView.setBackgroundResource(ic_star_border_black_24dp);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onError(ANError error) {
Log.d(TAG, "onError: " + error);
}
});
if (myViewHolder.btn.isPressed()){
}
}
else {
}
}
});
Finally i solved it correctly
first i needed to create php file where it checks in which state
$user_id = $_POST['user_id'];
$post_id = $_POST['post_id'];
$sql_verify = "SELECT * FROM likes_table WHERE post_id = :POST_ID AND user_id =
:USER_ID
";
$stmt = $PDO->prepare($sql_verify);
$stmt->bindParam(':POST_ID', $post_id);
$stmt->bindParam(':USER_ID',$user_id);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$returnApp = array( 'SIGNUP' => 'LIKE_ALREADY_EXIST');
echo json_encode($returnApp);
}
else {
$returnApp = array( 'SIGNUP' => 'LIKE_DOESNT_EXIST');
echo json_encode($returnApp);
}
then i create mothod for calling it with two cases one when toggle button is on and the onther when the toggle button is off
private void getdata3(final MyViewHolder myViewHolder , final int i){
final String URL2 = HOST + "/likes_table2.php";
sessionManager = new SessionManager(zContext);
final HashMap<String, String> user = sessionManager.getUserDetail();
final String user_id3 = user.get(USER_ID);
PostsModelClass data = modelClassList.get(i);
final String post_id = data.getPost_id();
Ion.with(zContext)
.load(URL2)
.setBodyParameter("user_id",user_id3)
.setBodyParameter("post_id",post_id)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
try {
String RETURN = result.get("SIGNUP").getAsString();
switch (RETURN) {
case "LIKE_ALREADY_EXIST":
final String URL = HOST + "/dislike.php";
myViewHolder.btn.setBackgroundResource(ic_star_black_24dp_checked);
myViewHolder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Ion.with(zContext)
.load(URL)
.setBodyParameter("post_id", post_id)
.setBodyParameter("user_id",user_id3)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
try {
String RETURN = result.get("SIGNUP").getAsString();
switch (RETURN) {
case "Posted":
myViewHolder.btn.setBackgroundResource(ic_star_border_black_24dp);
getdata3(myViewHolder,i);
modelClassList.clear();
newsFeedFragmentUser.getData();
break;
default:
break;
}
} catch (Exception error) {
}
}
});
}
});
break;
case "LIKE_DOESNT_EXIST":
myViewHolder.btn.setBackgroundResource(ic_star_border_black_24dp);
final String URL3 = HOST + "/likes_table.php";
myViewHolder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Ion.with(zContext)
.load(URL3)
.setBodyParameter("post_id", post_id)
.setBodyParameter("user_id",user_id3)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
try {
String RETURN = result.get("SIGNUP").getAsString();
switch (RETURN) {
case "Posted":
myViewHolder.btn.setBackgroundResource(ic_star_black_24dp_checked);
getdata3(myViewHolder,i);
modelClassList.clear();
newsFeedFragmentUser.getData();
break;
default:
break;
}
} catch (Exception error) {
}
}
});
}
});
break;
default:
Toast.makeText(zContext, "Ops! Error Occurred m", Toast.LENGTH_LONG).show();
break;
}
} catch (Exception error) {
Toast.makeText(zContext, "Ops! Error Occured" + error, Toast.LENGTH_LONG).show();
}
}
});
}
then i call it inside onBindViewHolder
getdata3(myViewHolder,i);
hope this finds anyone in need of this .. it took my 3 days to figure out the logic
Related
I have an activity with several buttons . Each button loads a json data to the recyclerview from a json link.The problem with Volley here is
1) It loads the JSON data in the recyclerview only after I click the button two times (CLICK , GO BACK AND THEN CLICK).
2) When I try to load the JSON data for other buttons , my data gets replicated and the list is not cleared.
3) If I manually clear the list using json_list.clear() then I get an empty recycler view.
This is my code...
public class PreviousQuestionPapers2 extends AppCompatActivity {
TextView firstYear;
TextView secondYear;
TextView thirdYear;
TextView fourthYear;
PopulateListsForClasses p1=new PopulateListsForClasses();
Parcelable parcelable;
List<SingleItemDetails> listToSend;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prev_question_papers_second_dashboard);
firstYear=findViewById(R.id.FIRST_YEAR);
secondYear=findViewById(R.id.SECOND_YEAR);
thirdYear=findViewById(R.id.THIRD_YEAR);
fourthYear=findViewById(R.id.FOURTH_YEAR);
listToSend=new ArrayList<SingleItemDetails>();
final String branch = getIntent().getStringExtra("branch");
firstYear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (branch)
{
case "it":
populate_it_first_year();
listToSend = getList_to_return();
moveToNextActivity();
break;
case "cse":
populate_cse_first_year();
listToSend = getList_to_return();
moveToNextActivity();
break;
default:
Toast.makeText(PreviousQuestionPapers2.this,"UNDEFINED!",Toast.LENGTH_SHORT).show();
}
}
});
secondYear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (branch)
{
case "it":
populate_it_second_year();
listToSend =getList_to_return();
moveToNextActivity();
break;
case "cse":
populate_cse_second_year();
listToSend = getList_to_return();
moveToNextActivity();
break;
default: Toast.makeText(PreviousQuestionPapers2.this,"UNDEFINED!",Toast.LENGTH_SHORT).show();
}
}
});
List<SingleItemDetails>json_list=new ArrayList<>();
String myurl;
public List<SingleItemDetails> getList_to_return()
{
return json_list;
}
public void FetchJSONData(String url) {
String JSON_URL = url;
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
//JSONObject songObject = response.getJSONObject(i);
JSONObject movieObject = response.getJSONObject(i);
SingleItemDetails mov = new SingleItemDetails();
mov.setTitle(movieObject.getString("title"));
mov.setUrlForDownload(movieObject.getString("urlForDownload"));
json_list.add(mov);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("tag", "onErrorResponse: " + error.getMessage());
}
});
queue.add(jsonArrayRequest);
}
public void moveToNextActivity()
{
parcelable = Parcels.wrap(listToSend);
Intent intent = new Intent(PreviousQuestionPapers2.this, RecyclerMainActivity.class);
intent.putExtra("listToDisplay", parcelable);
startActivity(intent);
}
public void populate_it_first_year()
{
myurl = "http://www.json-generator.com/api/json/get/bUcmgeeCJK?indent=2";
FetchJSONData(myurl);
}
public void populate_it_second_year() {
myurl ="http://www.json-generator.com/api/json/get/bOOxdXLLWW?indent=2";
FetchJSONData(myurl);
}
public void populate_cse_first_year () {
myurl ="http://www.json-generator.com/api/json/get/ckWYWzcqrm?indent=2";
}
public void populate_cse_second_year () {
myurl ="http://www.json-generator.com/api/json/get/clAEQTAhQi?indent=2";
}
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've an activity whuich load some data from mySql db to populate a Recyclerview.
PollActivity.java (relevant code)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll);
rv = findViewById(R.id.rv);
// *** Rv Init ***
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(false);
polls = new ArrayList<>();
// SqLite data management
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
final String userid = user.get("uid");
// Local data
String localBefore = Locale.getDefault().getLanguage().toUpperCase();
final String local;
switch (localBefore){
case "IT":
local = "IT";
break;
case "FR":
local = "FR";
break;
case "DE":
local = "DE";
break;
case "ES":
local = "ES";
break;
default:
local = "EN";
break;
}
// ************
// *** MAIN ***
// ************
// Tag used to cancel the request
String tag_string_req = "req_login";
MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
.title(R.string.strDialogProgressLoading_title)
.content(R.string.strDialogProgressReg_desc)
.progress(true, 0);
final MaterialDialog myDialog = builder.build();
myDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_LOADING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
for(int i=0; i<jObj.length()-2; i++){
int j = i + 1;
JSONObject pollObject = jObj.getJSONObject("poll" + i);
JSONObject pollObjectNext = jObj.getJSONObject("poll" + j);
i++;
//Id to String Translate
int idInterests = getResources().getIdentifier("strInterestsItem" + pollObject.getString("id_interests"), "string", getPackageName());
String strInterests = getString(idInterests);
String strPoint;
if(pollObject.getString("sponsor").equals("UUABA")){
strPoint = "+200";
}else{
strPoint = "+150";
}
//String concatenation
String idPoll = "#" + pollObject.getString("id_poll");
String strQuestion = "#" + pollObject.getString("poll_question");
String IdUser = userid;
polls.add(new Poll(idPoll
, pollObject.getString("sponsor")
, pollObject.getString("poll_user_state")
, IdUser
, strInterests
, strQuestion
, pollObject.getString("poll_answer")
, pollObject.getString("id_poll_answer")
, pollObjectNext.getString("poll_answer")
, pollObjectNext.getString("id_poll_answer")
, strPoint));
}
initializeAdapter();
myDialog.dismiss();
} else {
myDialog.dismiss();
// Error in loading. Get the error message
String errorMsg = jObj.getString("error_msg");
int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
String strErrorRes = getString(idErrorRes);
//POPUP ERRORE
new MaterialDialog.Builder(PollActivity.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(strErrorRes)
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
myDialog.dismiss();
//POPUP ERRORE
new MaterialDialog.Builder(PollActivity.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to loading url
Map<String, String> params = new HashMap<String, String>();
params.put("userid", userid);
params.put("local", local);
//Log.d("NINJA", "UserID: " + userid);
//Log.d("NINJA", "Local: " + local);
return params;
}
};
// Adding request to request queue
AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);
// ************
// ************
// ************
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(polls);
rv.setAdapter(adapter);
}
public void reloadActivity(){
startActivity(getIntent());
finish();
}
}
RVAdapter.java(my Recycler View Adapter)
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PollViewHolder> {
public static class PollViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView txtIdPoll;
ImageView imgSponsor;
ImageView imgNew;
TextView txtIdInterests;
TextView txtQuestion;
RadioGroup radioGroupAnswers;
RadioButton radioAnswer1;
RadioButton radioAnswer2;
Button btnPoint;
PollViewHolder(View itemView) {
super(itemView);
cv = itemView.findViewById(R.id.cv);
txtIdPoll = itemView.findViewById(R.id.txtIdPoll);
imgSponsor = itemView.findViewById(R.id.imgSponsor);
imgNew = itemView.findViewById(R.id.imgNew);
txtIdInterests = itemView.findViewById(R.id.txtIdInterests);
txtQuestion = itemView.findViewById(R.id.txtQuestion);
radioGroupAnswers = itemView.findViewById(R.id.radioGroupAnswers);
radioAnswer1 = itemView.findViewById(R.id.radioAnswer1);
radioAnswer2 = itemView.findViewById(R.id.radioAnswer2);
btnPoint = itemView.findViewById(R.id.btnPoint);
}
}
List<Poll> polls;
//Context context;
public RVAdapter(List<Poll> polls){
this.polls = polls;
//this.context = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PollViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.poll_item, viewGroup, false);
PollViewHolder pvh = new PollViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(final PollViewHolder pollViewHolder, final int i) {
final int rb1id = 1000;
final int rb2id = 2000;
//Setting RadioButton ID
pollViewHolder.radioAnswer1.setId(rb1id);
pollViewHolder.radioAnswer2.setId(rb2id);
pollViewHolder.txtIdPoll.setText(polls.get(i).txtIdPoll);
if(polls.get(i).txtSponsor.equals("UUABA")){
pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_logo_red_bg);
}else{
pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_sponsor_green_bg);
}
if(polls.get(i).txtNew.equals("0")){
pollViewHolder.imgNew.setImageResource(R.drawable.ic_new);
}else{
pollViewHolder.btnPoint.setEnabled(false);
pollViewHolder.btnPoint.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
}
pollViewHolder.txtIdInterests.setText(polls.get(i).txtIdInterests);
pollViewHolder.txtQuestion.setText(polls.get(i).txtQuestion);
pollViewHolder.radioAnswer1.setText(polls.get(i).txtAnswer1);
pollViewHolder.radioAnswer2.setText(polls.get(i).txtAnswer2);
pollViewHolder.btnPoint.setText(polls.get(i).txtPoint);
pollViewHolder.btnPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId() == -1){
Snackbar snackbar = Snackbar.make(v, R.string.strSnackPoll, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
TextView textView =snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}else{
QueryUtils queryUtils = new QueryUtils();
String IdPoll = String.valueOf((polls.get(i).txtIdPoll)).replace("#", "");
switch (pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId()){
case 1000:
queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer1)));
break;
case 2000:
queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer2)));
break;
}
}
}
});
}
#Override
public int getItemCount() {
return polls.size();
}
}
At this point, I would like to update a db field at button click and reload PollActivity.java to force the RecyclerView update (I'd like that the NEW image disappear from the updated CardView). I guess to do this calling a method of my QueryUtils.java (one of the method it will contain), avoiding to write too mutch code inside adapter.
QueryUtils.java
#SuppressLint("Registered")
public class QueryUtils extends Application {
private String tag_string_req = "req_poll_answer_upg";
public void upgPollAnswer(final String UserId, final String PollId, final String AnswerId){
Log.d("NINJA", "Utente: " + UserId);
Log.d("NINJA", "Poll: " + PollId);
Log.d("NINJA", "Risposta: " + AnswerId);
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_ANSWER_UPG, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if (!error) {
Log.d("NINJA", "Messaggio: " + message);
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();
} else {
//myDialog.dismiss();
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
String strErrorRes = getString(idErrorRes);
Log.d("NINJA", "ErrorePhP: " + strErrorRes);
//POPUP ERRORE
/*new MaterialDialog.Builder(QueryUtils.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(strErrorRes)
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("NINJA", "ErroreVolley: " + error);
//myDialog.dismiss();
//POPUP ERRORE
/*new MaterialDialog.Builder(QueryUtils.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();*/
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to loading url
Map<String, String> params = new HashMap<String, String>();
params.put("userid", UserId);
params.put("id_poll", PollId);
params.put("id_answer", AnswerId);
return params;
}
};
// Adding request to request queue
AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
At the end of the update procedure, I call the reloadActivity method in PollActivity, to reload itself. THIS call generate the error below:
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4226)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:751)
at android.app.Activity.startActivity(Activity.java:4522)
at android.app.Activity.startActivity(Activity.java:4490)
at com.uuaba.uuaba.core.PollActivity.reloadActivity(PollActivity.java:345)
at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:48)
at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:33)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I'm new in Android programming and I tried different solution found in this great forum, but none of them worked for me.
Please help me
Problem is that you are trying to create a new instance of activity without the use of intent :
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();
You should replace this code with the following lines:
public void onClickChangeActivity() {
Intent intent = new Intent(this, PollActivity.class);
startActivity(intent);
}
But your solution is far away from the ideal solutions available in the market. Restarting the activity whenever there is a change in data because you have to update data can never be a good way to go.
Try considering one of these ways to prevent activity restart
Create a data stream(list of data) and keep on reading that on
activity level.
Create a local broadcast receiver
Do let me know if you need help in above ways.
As a quick fix for the problem you can use this hackish way
Create a callback
interface Result {
void success(ResponseModel model);
void failure(Throwable throw);
}
In QueryUtils
List resultCallbacks = new ArrayList(); public void
addCallback(Result result) { resultCallbacks.add(result); }
create List resultCallbacks and a method addCallback to add the callbacks
In PollsActivity write this
((QueryApplication)getApplicationContext().getApplication()).addCallbacks(this);
and implement the callback.
On receiving any data update your list and do
RVUpdater.notifyDataSetChanged();
Hope this will help.
I'm inflating dynamic view to linear layout but it displays reversely.
try {
JSONArray jsonArray = new JSONArray(tooteet.getMeasureJson());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Measure measureData = new Measure();
measureData.id = jsonObject.optString("id");;
measureData.tooteetId = jsonObject.optString("tooteetId");
measureData.laneId = jsonObject.optString("laneId");
measureData.startDate = jsonObject.optString("startDate");
measureData.endDate = jsonObject.optString("endDate");
measureData.description = jsonObject.optString("text");
measureData.value = jsonObject.optDouble("value");
measureData.measureTypeId = jsonObject.optInt("measureTypeId");
measureData.description = jsonObject.optString("text");
measureData.isTimeSet =jsonObject.optBoolean("isTimeSet");
mMeasureList.add(measureData);
addMeasureView(measureData, i);
}
} catch (Exception e) {
Log.d("FeedMeasure", "Exception: "+e.toString());
}
where i'm getting log value for tooteet.getMeasureJson() is
onCreate -- tooteet.getMeasureJson(): [{"id":"3fb2af41-201d-4aca-9479-42af6cca5947","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":11111,"text":"","measureTypeId":1,"isTimeSet":false},{"id":"ecab9659-7eb5-417a-8f5e-f769629957ae","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":22222,"text":"","measureTypeId":1,"isTimeSet":false}]
Here I'm adding measure view using below method
private void addMeasureView(final Measure measure, int position) {
Log.d("ss","adding measure data value ________________"+measure.value+" position __________"+position);
final View parent = getLayoutInflater().inflate(R.layout.view_measure_tooteet_item, mDisplayContainer, false);
final TextView txtDescription, txtValues, txtStartDateTime, txtEndDateTime, labelTaxIncluded, labelTaxColon;
final ImageView imgEdit, imgDelete;
final LinearLayout lnrDescription, lnrStartLayout, lnrEndLayout;
final View mViewDivider;
txtDescription = (TextView) parent.findViewById(R.id.txt_description);
txtValues = (TextView) parent.findViewById(R.id.values);
txtStartDateTime = (TextView) parent.findViewById(R.id.start_date_and_time);
txtEndDateTime = (TextView) parent.findViewById(R.id.end_date_and_time);
mViewDivider = (View) parent.findViewById(R.id.view_divider);
imgEdit = (ImageView) parent.findViewById(R.id.edit);
imgDelete = (ImageView) parent.findViewById(R.id.delete);
lnrDescription = (LinearLayout) parent.findViewById(R.id.lnr_description);
lnrStartLayout = (LinearLayout) parent.findViewById(R.id.lnr_start_layout);
lnrEndLayout = (LinearLayout) parent.findViewById(R.id.lnr_end_layout);
if(tooteet.isOwner(getUserPreference())){
imgDelete.setVisibility(View.VISIBLE);
imgEdit.setVisibility(View.VISIBLE);
}else{
imgDelete.setVisibility(View.GONE);
imgEdit.setVisibility(View.GONE);
}
if(measure.getValue() > 0) {
txtValues.setVisibility(View.VISIBLE);
if (measure.getValue() % 1 == 0) {
txtValues.setText("" + (int) measure.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
} else {
txtValues.setText("" + measure.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
}
}else{
txtValues.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measure.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getStartDate())) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTime(measure.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getEndDate())) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTime(measure.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
//
// if(position < mMeasureList.size()){
// mViewDivider.setVisibility(View.VISIBLE);
// }else{
// mViewDivider.setVisibility(View.GONE);
// }
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setTitle(R.string.delete);
builder.setMessage(R.string.delete_tooteet_measure_tuple);
builder.setPositiveButton(R.string.yes_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
getDairyLineApi().deleteMeasureTooteet(mMeasureList.get(pos).getId(), tooteet.getLaneId(), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.deleted_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDisplayContainer.removeView(parent);
mMeasureList.remove(pos);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
});
builder.setNegativeButton(R.string.no_caps, null);
builder.create().show();
}
});
imgEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
MeasureTooteetSelector measureTooteetSelector = new MeasureTooteetSelector();
measureTooteetSelector.openMeasureDetailSelector(FeedMeasureDetailsActivity.this, mMeasureList.get(pos),
new MeasureTooteetSelector.OnMeasureDetailSelectListener() {
#Override
public void onMeasureSelect(final Measure measureData) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
if (measureData != null) {
mMeasureList.set(pos, measureData);
}
getDairyLineApi().updateMeasureTooteet(mMeasureList.get(pos), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.updated_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (measureData != null) {
mMeasureList.set(pos, measureData);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
mActionToSend = ACTION_MEASURE_UPDATE;
if (measureData.getValue() % 1 == 0) {
txtValues.setText("" + (int) measureData.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
} else {
txtValues.setText("" + measureData.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
}
Log.d("TAG", "measureData.getStartDate(): "+measureData.getStartDate());
if(!TextUtils.isEmpty(measureData.getStartDate()) && !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
Log.d("TAG", "measureData.getEndDate(): "+measureData.getEndDate());
if(!TextUtils.isEmpty(measureData.getEndDate())&& !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measureData.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measureData.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
}
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
#Override
public void onCancel() {
}
});
}
});
imgEdit.setTag(position);
imgDelete.setTag(position);
addView(parent);
}
My log inside addMeasureView is below:
adding measure data value ________________11111.0 position __________0
adding measure data value ________________22222.0 position __________1
But when i'm viewing this it in layout as this order
adding measure data value ________________22222.0
adding measure data value ________________11111.0
Please suggest me any idea.
This is my model class I'm using for getValue()
import com.kwypesoft.lanes.create_tooteet.LocalTooteetCreator;
import com.kwypesoft.lanes.utils.DateConversion;
import com.kwypesoft.lanes.utils.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
public class Measure implements Serializable{
// "id": "398627f1-9392-4b3f-8741-903fbcbbd3be",
// "tooteetId": "ab36f69e-a0c8-4f31-aa8d-9b4038a76d57",
// "laneId": "00000000-0000-0000-0000-000000000000",
// "startDate": "2016-04-26T08:00:00",
// "endDate": "2016-04-27T10:00:00",
// "value": 125.6500000000000,
// "measureTypeId": 20
public String id;
public String tooteetId;
public String laneId;
public String startDate;
public String endDate;
public String description;
public double value;
public int measureTypeId;
public boolean isTimeSet;
public Measure() {
}
public Measure(JSONArray jsonArray) {
try {
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
id = jsonObject.optString("id");
tooteetId = jsonObject.optString("tooteetId");
laneId = jsonObject.optString("laneId");
startDate = jsonObject.optString("startDate");
endDate = jsonObject.optString("endDate");
description = jsonObject.optString("text");
value = jsonObject.optDouble("value");
measureTypeId = jsonObject.optInt("measureTypeId");
isTimeSet = jsonObject.optBoolean("isTimeSet");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String getMeasureJSON(ArrayList<LocalTooteetCreator.MeasureData> data) {
JSONArray jsonArray = new JSONArray();
for (LocalTooteetCreator.MeasureData items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", items.value);
jsonObject.put("text", items.description);
jsonObject.put("measureTypeId", items.measureTypeId);
if(items.startDate != -1){
jsonObject.put("startDate", DateConversion.getDateWithTFromMilliSeconds(items.startTime, items.startDate));
}
if(items.endDate != -1){
jsonObject.put("endDate", DateConversion.getDateWithTFromMilliSeconds(items.endTime, items.endDate));
}
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public static String getMeasureDetailJSON(ArrayList<Measure> data) {
JSONArray jsonArray = new JSONArray();
for (Measure items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", items.id);
jsonObject.put("tooteetId", items.tooteetId);
jsonObject.put("laneId", items.laneId);
if(!TextUtils.isEmpty(items.startDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("startDate", items.startDate);
}
if(!TextUtils.isEmpty(items.endDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("endDate", items.endDate);
}
jsonObject.put("text", items.description);
jsonObject.put("value", items.value);
jsonObject.put("measureTypeId", items.measureTypeId);
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public String getId() {
return id;
}
public String getTooteetId() {
return tooteetId;
}
public String getLaneId() {
return laneId;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public double getValue() {
return value;
}
public int getMeasureTypeId() {
return measureTypeId;
}
public boolean getIsTimeSet() {
return isTimeSet;
}
public String getDescription() {
return description;
}
public boolean isTimeSet() {
return isTimeSet;
}
}
Hi I have done a mistake in addview method. Before my addview method is
mDisplayContainer.addView(view, mDisplayContainer.getChildCount() - 1);
Now i changed
mDisplayContainer.addView(view);
Its Working for me. Thank u so much for your comments
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);