Volley POST to send multiple JSON - java

I have a problem with a volley to send multiple JSON with StringRequest, I think the problem is in the hashmap un getParms()
public class MainActivity extends AppCompatActivity {
private static final String TAG = "ENCUESTA";
private static final String VERSION = "2.0.0.3";
private int totalEncuestas=0;
private Encuestador encuestador;
Button btnRutEncuestador;
Button btnEmisivo;
Button btnReceptivo;
Button btnEnvioData;
EditText txtRut;
EditText txtDV;
EditText txtDebug;
TextView lblVersion;
private JSONObject itemEnviar;
private int contador;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
encuestador = new Encuestador();
btnRutEncuestador = (Button) findViewById(R.id.btnRutEncuestador);
btnEmisivo = (Button) findViewById(R.id.btnEmisivo);
btnReceptivo = (Button) findViewById(R.id.btnReceptivo);
btnEnvioData = (Button) findViewById(R.id.btnEnvioData);
txtRut = (EditText) findViewById(R.id.txtRut);
txtDV = (EditText) findViewById(R.id.txtDV);
lblVersion = (TextView) findViewById(R.id.lblVersion);
//DEBUG
//btnReceptivo.setEnabled(true);
//btnEmisivo.setEnabled(true);
lblVersion.setText(Util.getVersion());
//region SIN USO
/*ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if(!Util.leerArchivo(MainActivity.this, "data.txt").isEmpty()) {
if(Util.verificaConexion(MainActivity.this)) {
Log.d(TAG, "Enviando información");
RequestQueue MyRequestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.inicial.cl/android/set.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.isEmpty() && response.equalsIgnoreCase("success")) {
Log.d(TAG, "success, elimina data local");
Util.vaciarEncuesta(MainActivity.this);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onError: " + error);
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
try {
MyData.put("data", Util.leerArchivo(MainActivity.this, "data.txt"));
} catch (Exception e) {
Log.e(TAG, "Error al enviar: " + e.getMessage());
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}else{
Log.d(TAG, "Sin internet");
}
}else{
Log.d(TAG, "Sin data");
}
}
}, 0, 5, TimeUnit.MINUTES);*/
/*txtRut.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
String txt = Util.getTextFromEditText(txtRut);
if(!txt.isEmpty() && txt.equalsIgnoreCase("123123"))
{
txtDebug.setVisibility(View.VISIBLE);
txtDebug.setText(Util.leerArchivo(MainActivity.this, "data.txt"));
}else
{
txtDebug.setVisibility(View.GONE);
txtDebug.setText("");
}
}
});*/
//endregion
//region btnRutEncuestador
btnRutEncuestador.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strRut = txtRut.getText().toString();
String strDV = txtDV.getText().toString();
if (strRut.isEmpty()) {
Toast.makeText(getApplicationContext(), "Debe ingresar rut", Toast.LENGTH_SHORT).show();
return;
}
if (strDV.isEmpty()) {
Toast.makeText(getApplicationContext(), "Debe ingresar DV", Toast.LENGTH_SHORT).show();
return;
}
Boolean existeEncuestador = false;
for (Encuestador e : Encuestador.getAllEncuestadores()) {
Log.d(TAG, "RutIngresado=" + strRut + "-" + strDV + " RutBase:" + e.getRut() + "-" + e.getDv());
if (strRut.equalsIgnoreCase(e.getRut()) && strDV.equalsIgnoreCase(e.getDv())) {
encuestador = new Encuestador();
encuestador.setRut(strRut);
encuestador.setDv(strDV);
btnReceptivo.setEnabled(true);
btnEmisivo.setEnabled(true);
existeEncuestador = true;
break;
} else {
existeEncuestador = false;
}
}
if (!existeEncuestador) {
Util.alertDialog(MainActivity.this, "El Rut ingresado no esta habilitado para realizar encuestas",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
}
});
//endregion
//region btnEmisivo
btnEmisivo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), EmisivoActivity.class);
intent.putExtra("ENCUESTADOR", encuestador);
startActivity(intent);
}
});
//endregion
//region btnReceptivo
btnReceptivo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ReceptivoActivity.class);
intent.putExtra("ENCUESTADOR", encuestador);
startActivity(intent);
}
});
//endregion
//region btnEnvioData
btnEnvioData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnEnvioData.setEnabled(false);
if (!Util.leerArchivo(MainActivity.this, "data.txt").isEmpty()) {
if (Util.verificaConexion(MainActivity.this)) {
Log.d(TAG, "Enviando información");
try {
JSONArray list = new JSONArray(Util.leerArchivo(MainActivity.this, "data.txt"));
totalEncuestas = list.length();
setContador(0);
for (int i = 0; i < list.length(); i++) {
Log.d(TAG, "DATA:"+list.getJSONObject(i));
setItemEnviar(list.getJSONObject(i));
sendRequest();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Sin internet");
Util.alertDialog(MainActivity.this, "Error, no hay conexión a internet",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
}
} else {
Log.d(TAG, "Sin data");
Util.alertDialog(MainActivity.this, "Sin encuestas que enviar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
}
}
});
//endregion
}
public void sendRequest()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.inicial.cl/android/set.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.isEmpty() && response.equalsIgnoreCase("success")) {
setContador(getContador() + 1);
if(getContador() == totalEncuestas) {
Util.alertDialog(MainActivity.this, "Encuestas enviadas exitosamente!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
Util.vaciarEncuesta(MainActivity.this);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onError: " + error);
btnEnvioData.setEnabled(true);
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
try {
MyData.put("data"+Integer.toString(getContador()), getItemEnviar().toString().replaceAll("\n", ""));
Log.e(TAG, "enviados: " + getItemEnviar().toString());
} catch (Exception e) {
Log.e(TAG, "Error al enviar: " + e.getMessage());
btnEnvioData.setEnabled(true);
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
MyRequestQueue.getCache().clear();
}
public JSONObject getItemEnviar() {
return itemEnviar;
}
public void setItemEnviar(JSONObject itemEnviar) {
this.itemEnviar = itemEnviar;
}
public int getContador() {
return contador;
}
public void setContador(int contador) {
this.contador = contador;
}
}
The problem is when I get the data to send, in the for the JSON for send are ok, but in the getparms() this only set the last JSON for send, and send many times of the total array

Related

How to start new activity from button in alert dialog?

In this app, I created scanner and the result will shown in alertDialogwith two button; OK and NEXT.NEXT button I would like to go to new activity.The problem is, when click the NEXT button, it crash.
please help me..
i'm new.
#Override
public void handleResult(final Result result) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(qrscanner.this);
}
});
builder.setNeutralButton("NEXT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(qrscanner.this,attend_form.class);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
this attend_form
public class attend_form extends AppCompatActivity {
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_rega;
RadioGroup battend;
EditText File,Ic;
String file_number,ic_no;
String attendance = "";
AlertDialog.Builder builder;
String url_reg = "http://192.168.1.7/spm/android/attendance/attend.php";
File file;
Dialog dialog;
LinearLayout mContent;
View view;
signature mSignature;
Bitmap bitmap;
// Creating Separate Directory for saving Generated Images
String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/";
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String StoredPath = DIRECTORY + pic_name + ".png";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attend_form);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Setting ToolBar as ActionBar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btn_rega = (Button)findViewById(R.id.btn_rega);
final RadioGroup battend = (RadioGroup)findViewById(R.id.attendance);
final RadioButton attend = (RadioButton)findViewById(R.id.btn_attend);
final RadioButton absent = (RadioButton)findViewById(R.id.btn_absent);
// Button to open signature panel
btn_get_sign = (Button) findViewById(R.id.signature);
File = (EditText)findViewById(R.id.file_number);
Ic = (EditText)findViewById(R.id.ic_no);
builder = new AlertDialog.Builder(attend_form.this);
btn_rega.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
file_number = File.getText().toString();
ic_no = Ic.getText().toString();
if (battend.getCheckedRadioButtonId() == attend.getId())
{
attendance = "ATTEND";
}
else if(battend.getCheckedRadioButtonId() == absent.getId())
{
attendance = "ABSENT";
}
if(file_number.equals("") || ic_no.equals(""))
{
builder.setTitle("Something were wrong");
builder.setMessage("Please fill all field");
displayAlert("input_error");
}
else
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_reg, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
builder.setTitle("Server Response");
builder.setMessage(message);
displayAlert(code);
}catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#SuppressWarnings("deprecation")
#Override
protected Map<String, String> getPostParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("file_number",file_number);
params.put("ic_no",ic_no);
params.put("attendance",attendance);
return super.getPostParams();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("file_number",file_number);
params.put("ic_no",ic_no);
params.put("attendance",attendance);
return params;
}
};
MySingleton.getInstance(attend_form.this).addToRequestque(stringRequest);
}
}
});
// Method to create Directory, if the Directory doesn't exists
file = new File(DIRECTORY);
if (!file.exists()) {
file.mkdir();
}
// Dialog Function
dialog = new Dialog(attend_form.this);
// Removing the features of Normal Dialogs
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_signature);
dialog.setCancelable(true);
btn_get_sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Function call for Digital Signature
dialog_action();
}
});
}
public void displayAlert(final String code)
{
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if(code.equals("input_error"))
{
File.setText("");
Ic.setText("");
}
else if(code.equals("reg_success"))
{
finish();
}
else if(code.equals("reg_failed"))
{
File.setText("");
Ic.setText("");
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
// Function for Digital Signature
public void dialog_action() {
mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
mSignature = new signature(getApplicationContext(), null);
mSignature.setBackgroundColor(Color.WHITE);
// Dynamically generating Layout through java code
mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mClear = (Button) dialog.findViewById(R.id.clear);
mGetSign = (Button) dialog.findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button) dialog.findViewById(R.id.cancel);
view = mContent;
mClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});
mGetSign.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
view.setDrawingCacheEnabled(true);
mSignature.save(view, StoredPath);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Successfully Saved", Toast.LENGTH_SHORT).show();
// Calling the same class
recreate();
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Canceled");
dialog.dismiss();
// Calling the same class
recreate();
}
});
dialog.show();
}
public class signature extends View {
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void save(View v, String StoredPath) {
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if (bitmap == null) {
bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(bitmap);
try {
// Output the file
FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
v.draw(canvas);
// Convert the output file to Image such as .png
bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
Log.v("log_tag", e.toString());
}
}
public void clear() {
path.reset();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void debug(String string) {
Log.v("log_tag", string);
}
private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY) {
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
}
StringRequestClass
public class StringRequestClass extends AsyncTask<String, Void, String> {
//Your task happens here
EditText File,Ic;
String file_number,ic_no;
String attendance = "";
AlertDialog.Builder builder;
String url_reg = "http://192.168.1.7/spm/android/attendance/attend.php";
#Override
protected String doInBackground(String... params) {
//Do your StringRequest here.
if(file_number.equals("") || ic_no.equals(""))
{
builder.setTitle("Something were wrong");
builder.setMessage("Please fill all field");
displayAlert("input_error");
}
return null;
}
//Things to do when your task is complete.
#Override
protected void onPostExecute(String result) {
//Do everything you want to do after the StringRequest is completed.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_reg, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
builder.setTitle("Server Response");
builder.setMessage(message);
displayAlert(code);
}catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("file_number",file_number);
params.put("ic_no",ic_no);
params.put("attendance",attendance);
return params;
}
};
MySingleton.getInstance(attend_form.this).addToRequestque(stringRequest);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if(file_number.equals("") || ic_no.equals(""))
{
builder.setTitle("Something were wrong");
builder.setMessage("Please fill all field");
displayAlert("input_error");
}
} //Things to do before the internet-related task
#Override
protected void onProgressUpdate(Void... values) {}
public void displayAlert(final String code)
{
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if(code.equals("input_error"))
{
File.setText("");
Ic.setText("");
}
else if(code.equals("reg_success"))
{
finish();
}
else if(code.equals("reg_failed"))
{
File.setText("");
Ic.setText("");
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Try to use getContext()
Intent intent = new Intent(getContext(), attend_form.class);
getContext().startActivity(intent);

Multiple layout setVisibility wont show correct layout after getting pressed on certain layout

I have a layout in which there are several other layouts by including in XML, I add some textviews as buttons to change the view layouts from one layout to another.
I display each layout with the setVisibility method between layouts, with setOnClickListener in the textview.
The problem is just after finishing displaying the "profile" layout and trying to display the "about us" layout, the system displays a "profile" layout instead of the "about us" layout.
Here is myJava
public class SettingMenu extends AppCompatActivity {
View userProfile, settingLayout, userFavorite, UserEditProfile, aboutUS, contactUS, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
int x = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
settingLayout = findViewById(R.id.SettingLayout);
userProfile = findViewById(R.id.user_profile);
userProfile.setVisibility(View.GONE);
aboutUS = findViewById(R.id.AboutUs);
aboutUS.setVisibility(View.GONE);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (x == 0){
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
else if (x == 1){
x = 0;
UserEditProfile.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 2){
x = 0;
userFavorite.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 3) {
x = 0;
aboutUS.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 4){
x = 0;
settingLayout.setVisibility(View.VISIBLE);
contactUS.setVisibility(View.GONE);
}
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aboutUS.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
AboutUs();
x = x + 3;
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userProfile.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
UserProfile();
x = x + 1;
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
UPDATE
I change my method from setVisibility to setContentView
here's the code. it works fine for me
public class SettingMenu extends AppCompatActivity {
View UserEditProfile, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
ControllerHome();
}
private void ControllerHome() {
setContentView(R.layout.activity_setting);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AboutUs();
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserProfile();
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
setContentView(R.layout.setting_user_profile);
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
setContentView(R.layout.about_us);
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
solved by using setContentView rather than setVisibility.

start method only after checking is there a needed value in sharedPref

Theres edit text field. It has to work like this:
1) if it is empty - nothing happen
2) if user put some NEW text starts method of TextWatcher with HTTP request which takes JSON object. Also the value of String will put in sharedpreference
3) if user open activity when sharedpreference already have value of previous string it has to just set text from that string and don't start method of TextWatcher with HTTP request.
So there are three conditions and progrmm has to make request only in case when value of string is not tha same as in shared pref. Now it sends request even if person just open app. I want to avoid wrong requests and make request only after new value of string.
THE MAIN QUESTION: How to launch HTTP request code ONLY in case if value in textfield is not the same as in sharedpref?
P.S. If you think my question is bad. Please tell me in notes NOT JUST MAKE -1 please. Teach new programmers
Here is the code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
final String TAG = "myTag";
String language;
SharedPreferences mSettings;
SharedPreferences textReference;
SharedPreferences translateReference;
SharedPreferences longLangReference;
SharedPreferences shortLangReference;
final String SAVED_TEXT = "text";
final String SAVED_TRANSLATION = "translation";
final String LANGUAGE_LONG = "lang_long";
final String LANGUAGE_SHORT = "lang_short";
public static final String APP_PREFERENCES = "mysettings";
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
Log.v(TAG, "in afterTextChanged");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
saveText();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "in Oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
int textLength = translatedTextInput.getText().length();
translatedTextInput.setSelection(textLength);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(TAG, "in chooseLanguageListener");
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
if (mSettings.contains(LANGUAGE_LONG)){
Log.v(TAG, "here");
chooseLanguageButton.setText(mSettings.getString(LANGUAGE_LONG,""));
} else {
Log.v(TAG, "THERE");
chooseLanguageButton.setText("Choose language");
}
if (mSettings.contains(SAVED_TEXT)){
Log.v(TAG, "here");
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
} else {
Log.v(TAG, "boooooom");
}
if (mSettings.contains(SAVED_TRANSLATION)){
Log.v(TAG, "here in TRANSLATION FIELD" + mSettings.getString(SAVED_TRANSLATION,""));
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
} else {
Log.v(TAG, "boooooom");
}
}
#Override
protected void onResume() {
super.onResume();
translatedTextInput.post(new Runnable() {
#Override
public void run() {
Selection.setSelection(translatedTextInput, );
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mSettings = null;
}
void saveText() {
// mSettings = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
SharedPreferences.Editor ed = mSettings.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.putString(SAVED_TRANSLATION, translatedTextOutput.getText().toString());
ed.apply();
Log.v(TAG, "Text saved==========>" + translatedTextInput.getText().toString());
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
textReference = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
translateReference = getSharedPreferences(SAVED_TRANSLATION, MODE_PRIVATE);
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
Log.v(TAG, "IN LOAD TEXT METHOD" + mSettings.getString(SAVED_TEXT,""));
Log.v(TAG, "IN LOAD TRANSLATION METHOD" + mSettings.getString(SAVED_TRANSLATION,""));
}
public void sendJsonRequest() {
Log.v(TAG, "in sendJsonObject");
Intent myIntent = getIntent();
// language = myIntent.getStringExtra("short");
shortLangReference = getSharedPreferences(LANGUAGE_SHORT, MODE_PRIVATE);
language = mSettings.getString(LANGUAGE_SHORT,"");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}

Call number when click list view item

I have a contact list activity but want to add some functionality so that when you click on a contact it will begin calling their phone number. I have tried this code snippet but nothing happens when I tap on a contact:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + currentContact.getPhone()));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
try{
((Activity) context).startActivity(callIntent);
}catch (Exception e){
e.printStackTrace();
}
All Contact activity code:
public class ContactList extends ActionBarActivity {
Spinner spinner, spinnerFilter;
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
ImageView contactImageimgView, btnSort;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
//Uri imageUri = null;
AlertDialog alertDialog;
Bitmap photoTaken;
String userId;
boolean isReverseEnabledPriority = false, isReverseEnabledName = false;
//ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
userId = user.get("uid");
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
contactListView = (ListView) findViewById(R.id.listView);
contactImageimgView = (ImageView) findViewById(R.id.imgViewContactImage);
spinner = (Spinner) findViewById(R.id.spinner);
spinnerFilter = (Spinner) findViewById(R.id.spinnerFilter);
btnSort = (ImageView) findViewById(R.id.btnSort);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("add contact");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("List");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("contact list");
tabHost.addTab(tabSpec);
getContacts(ContactList.this);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filter = spinnerFilter.getSelectedItem().toString();
if(filter.equals("Priority")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getPriorityVal().compareTo(v2.getPriorityVal());
}
});
if(isReverseEnabledPriority)
Collections.reverse(Contacts);
isReverseEnabledPriority = !isReverseEnabledPriority;
populateList();
}else if(filter.equals("Name")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getName().compareTo(v2.getName());
}
});
if(isReverseEnabledName)
Collections.reverse(Contacts);
isReverseEnabledName = !isReverseEnabledName;
populateList();
}else{
Toast.makeText(ContactList.this, "Please selectr a method to sort..!", Toast.LENGTH_SHORT).show();
}
}
});
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Contact contact = new Contact(photoTaken, nameTxt.getText().toString(), phoneTxt.getText().toString(), emailTxt.getText().toString(), addressTxt.getText().toString(), spinner.getSelectedItem().toString(), userId);
Contacts.add(contact);
saveContact(contact, ContactList.this);
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageimgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
}
void getContacts(final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Please wait..", false);
}
});
try {
Contacts = ContactsController.getAllContactsOfUser(userId);
populateList();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
}.start();
}
void saveContact(final Contact contact, final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
boolean result = false;
int id;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Saving Contact..", false);
}
});
try {
id = ContactsController.saveContact(contact);
if(id > 0){
contact.setId(id);
result = ContactsController.uploadImage(contact);
}
} catch (Exception e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(id == 0){
Toast.makeText(context, "Contact is not saved..!", Toast.LENGTH_SHORT).show();
}
if(!result){
Toast.makeText(context, "Image upload failed..!", Toast.LENGTH_SHORT).show();
}else{
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1) {
Uri imageUri = data.getData();
try {
photoTaken = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
} catch (IOException e) {
e.printStackTrace();
}
contactImageimgView.setImageURI(data.getData());
}
}
}
private void populateList() {
ArrayAdapter<Contact> adapter = new ContactListAdapter();
contactListView.setAdapter(adapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(ContactList.this, R.layout.listview_item, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
final Contact currentContact = Contacts.get(position);
try {
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
TextView cPriority = (TextView) view.findViewById(R.id.cPriority);
cPriority.setText(currentContact.getPriority());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
if(currentContact.getImage() != null)
ivContactImage.setImageBitmap(currentContact.getImage());
} catch (Exception e) {
e.printStackTrace();
}
ImageView btnDeleteContact = (ImageView) view.findViewById(R.id.btnDeleteContact);
btnDeleteContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(ContactList.this);
builder.setTitle("Confirm Delete");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteContact(currentContact, ContactList.this);
alertDialog.dismiss();
}
});
builder.setNegativeButton("No", null);
alertDialog = builder.create();
alertDialog.show();
}
});
return view;
}
#Override
public int getCount() {
return Contacts.size();
}
void deleteContact( final Contact contact, final Context context){
new Thread(){
Handler handler = new Handler();
ProgressDialog progressDialog;
Boolean result = false;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Deleting Contact..", false);
}
});
try {
result = ContactsController.deleteContact(contact);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(!result){
Toast.makeText(context, "Contact delete failed..!", Toast.LENGTH_SHORT).show();
}else{
Contacts.remove(contact);
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been deleted from your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
}
}
Have you try this code??
Uri number = Uri.parse("tel:123456789");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);

How to set data from JSON?

I am new to android JSON programming. I want to use set and get function in this program ,but when i used get() for full_name,getting null.
public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
private void getLogin(JSONObject response) {
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
LoginBean loginBean = new LoginBean();
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
LoginBean loginBean = new LoginBean();
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
}
JSON Input:
"{
""user_name"":""ashish#soms.in"",
""user_password"":""123456"",
""device_token"":""1111"",
""mac_address"":""1111"",
""gps_latitude"":""1111"",
""gps_longitude"":""1111""
}"
Here is JSON Response:
{
""data"": {
""user_id"": ""90"",
""full_name"": ""ashish"",
""display_name"": ""ashish"",
""user_image"": ""images/noimage.png"",
""gender"": ""0"",
""authorization_key"": ""4eef1d65f7b470dbca881fe6452ec11457f54489""
}
}
pls comment line LoginBean loginBean = new LoginBean(); then try .
try this code
private void getLogin(JSONObject response) {
LoginBean loginBean=null;
if (response != null){
try {
loginBean = new LoginBean();
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}

Categories

Resources