this program is to get a name from online mysql database by entering an id and sending request to php online file and the response is the name
what is wrong with the code ? I get no name
xml
//activity_main.xml
<LinearLayout
android:orientation="vertical"
android:layout_height="495dp"
android:layout_width="368dp"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp"
tools:ignore="MissingConstraints">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editTextId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/buttonGet"
android:text="Get"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Main class
//MainActivity.class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject data = result.getJSONObject(0);
name = data.getString(Config.KEY_Name);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name);
}
#Override
public void onClick(View v) {
getData();
}
}
Config class
public class Config {
public static final String DATA_URL = "myPhpURL";
public static final String KEY_Name = "name";
public static final String JSON_ARRAY = "result";
}
You are not setting if you request is GET or POST, and you are not setting actual arguments for server. You are missing following piece of code
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("key", value);
return parameters;
}
Related
When submitting to Firebase, only photos are sent, without text and database as such.
I do according to the guide, but I don’t understand what is the reason.
The guide probably uses the deprecated getDownloadUrl() method, but the photo does not suffer from this. I do not understand the reason for this, since I am still new in this area, please help, I no longer understand what to do. To understand something, look at Maineenter image description here
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_im);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
Класс Upload
public class Upload {
private String mName;
private String mImageUrl;
public Upload(){
}
public Upload(String name, String imageUrl) {
this.mName = name;
this.mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = mName;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
this.mImageUrl = mImageUrl;
}
}
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="#+id/button_choose_im"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose" />
<EditText
android:id="#+id/edit_text_file_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/button_choose_im"
android:hint="Enter"
android:minHeight="48dp" />
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/progress_bar"
android:layout_below="#id/edit_text_file_name"
android:layout_marginTop="16dp" />
<ProgressBar
android:id="#+id/progress_bar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_upload"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp" />
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="Upload" />
<TextView
android:id="#+id/text_view_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button_upload"
android:layout_alignBottom="#+id/button_upload"
android:layout_marginStart="25dp"
android:layout_toEndOf="#+id/button_upload"
android:gravity="center"
android:text="Show"
android:textSize="16sp" />
</RelativeLayout>
I am using this library - https://github.com/stepstone-tech/android-material-stepper to build a step by step registration system where users will fill each field one by one before finally saving users data into the database using a php script via JSON.
I have 2 problems.
1. After filling the data, I dont kow how to save the data that has been inputed into the database.
2 How to validate each data been inputed individually onClick of 'NEXT' button. (Although, number 1 is much more important for now, but if someome could help me out with both, GREAT!.)
I have done this with the use of just one activity and it works fine.
One of the fragment. 6 of them (They are all similar)
public class EmailRegisterFragment extends Fragment implements Step {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_email_register, container, false);
//initialize your UI
return v;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
}
One of the fragementLayout (They are all similar)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".UsernameRegisterFragment"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/back_left_light"
android:layout_marginLeft="10dp"
android:clickable="true"
android:focusable="true"
android:onClick="goToWelcomePage"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Email Address"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:padding="20dp"
/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextTheme"
>
<EditText
android:layout_width="match_parent"
android:inputType="textEmailAddress"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Input Your Email"
android:textColor="#android:color/black"
android:id="#+id/email"
app:backgroundTint="#color/edit_text"
android:theme="#style/EditTextTheme"
android:textCursorDrawable="#null"
/>
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:onClick="goToRegisterWithPhone"
android:clickable="true"
android:text="You dont have an email? Click here"/>
</LinearLayout>
Activity layout (That shows the NEXT, BACK COMPLETE Button and progress bar)
<?xml version="1.0" encoding="utf-8"?>
<com.stepstone.stepper.StepperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/stepperLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:ms_stepperType="progress_bar"
app:ms_nextButtonColor="#color/white"
app:ms_completeButtonColor="#color/white"
app:ms_backButtonColor="#color/white"
/>
ActivityJava file
public class IntroActivity extends AppCompatActivity implements StepperLayout.StepperListener{
private StepperLayout mStepperLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
//remove action and status bar
if (getSupportActionBar() != null)
getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
mStepperLayout = (StepperLayout) findViewById(R.id.stepperLayout);
mStepperLayout.setAdapter(new MyStepperAdapter(getSupportFragmentManager(), this));
mStepperLayout.setListener(this);
}
#Override
public void onCompleted(View completeButton) {
Toast.makeText(this, "onCompleted!", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(VerificationError verificationError) {
Toast.makeText(this, "onError! -> " + verificationError.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onStepSelected(int newStepPosition) {
}
#Override
public void onReturn() {
finish();
}
public void goToWelcomePage(View view){
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
}
public void goToRegisterWithPhone(View view){
Intent intent = new Intent(this, IntroActivity.class);
startActivity(intent);
}
}
Like I said I have done this with the use of just one Activity using the Volley library. Check it out.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText username, email, password;
private Button btn_register_final;
private ProgressBar loading;
private TextView login_text;
private static String URL_REGISTER = "http://78d24f21.ngrok.io/misnap/register.php";
SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sessionManager = new SessionManager(this);
username = findViewById(R.id.etUsername);
email = findViewById(R.id.etEmail);
password = findViewById(R.id.etPassword);
btn_register_final = findViewById(R.id.btnRegisterFinal);
loading = findViewById(R.id.loading);
login_text = findViewById(R.id.btnLoginText);
btn_register_final.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something here after clicking register
Register();
}
});
login_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
v.getContext().startActivity(intent);
}
});
}
public void Register(){
loading.setVisibility(View.VISIBLE);
btn_register_final.setVisibility(View.GONE);
final String username = this.username.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
sessionManager.createSession(username, email);
Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
} catch (JSONException e){
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "Unable to register" + e.toString(),
Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Unable to register" + error.toString(),
Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Register.php
<?php
require_once("connect.php");
if ($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$password')";
if(mysqli_query($conn, $sql)){
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
}
else{
$result["success"] = "0";
$result["message"] = "An error occured";
echo json_encode($result);
mysqli_close($conn);
}
}
?>
How do use this same logic for the fragments??
this might be late but i think it would help to others. So for sure you can validate/Insert or whatever you want to do with your inputs on Next button click before going to next step, This is how you can do it in Kotlin
// To be somewhere inside your Step
override fun verifyStep(): VerificationError? {
if (validateStep()){
return null
}
else
VerificationError("Any error message")
}
Now here validateStep will be a function that returns True or false depending upon your needs. Here is a simple example of a validateStep() function. Here you can do anything like insertion or validation etc.
private fun validateStep(): Boolean {
var isValid = true
val name = binding.etCustomerName.text.toString()
val email = binding.etCustomerEmail.text.toString()
if (name.isEmpty()) {
isValid = false
}
if (email.isEmpty()) {
isValid = false
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
isValid = false
}
return isValid
}
Do let me know if it helps anyone. Happy coding :)
Please help me.
I have a problem with displaying image from MYSQL table with the path i get as response.
After login, I want to display user image which path found in the same record in the users table.
My java activity and XML file are :
public class HomeActivity extends AppCompatActivity {
private static final String TAG = HomeActivity.class.getSimpleName(); //getting the info
private TextView name, email,photo;
private Button btn_logout, btn_photo_upload;
SessionManager sessionManager;
String getId;
private static String URL_READ = "http://172.23.50.55/CP/read_detail.php";
private static String URL_EDIT = "http://172.23.50.55/CP/edit_detail.php";
private static String URL_UPLOAD = "http://172.23.50.55/CP/upload.php";
private Menu action;
private Bitmap bitmap;
CircleImageView profile_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
name = findViewById(R.id.name);
email = findViewById(R.id.email);
photo = findViewById(R.id.photo);
btn_logout = findViewById(R.id.btn_logout);
btn_photo_upload = findViewById(R.id.btn_photo);
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
btn_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
btn_photo_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseFile();
}
});
}
//getUserDetail
private void getUserDetail(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_READ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if (success.equals("1")){
for (int i =0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString("name").trim();
String strEmail = object.getString("email").trim();
// System.out.println("pspspspspspspspspspspspspspsp " + strEmail);
String strPhoto = object.getString("photo").trim();
name.setText(strName);
email.setText(strEmail);
photo.setText(strPhoto);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error Reading Detail "+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error Reading Detail "+error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String > params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
protected void onResume() {
super.onResume();
getUserDetail();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_action, menu);
action = menu;
action.findItem(R.id.menu_save).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_edit:
name.setFocusableInTouchMode(true);
email.setFocusableInTouchMode(true);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(name, InputMethodManager.SHOW_IMPLICIT);
action.findItem(R.id.menu_edit).setVisible(false);
action.findItem(R.id.menu_save).setVisible(true);
return true;
case R.id.menu_save:
SaveEditDetail();
action.findItem(R.id.menu_edit).setVisible(true);
action.findItem(R.id.menu_save).setVisible(false);
name.setFocusableInTouchMode(false);
email.setFocusableInTouchMode(false);
name.setFocusable(false);
email.setFocusable(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//save
private void SaveEditDetail() {
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String id = getId;
final String photo = this.photo.getText().toString().trim();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_EDIT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(HomeActivity.this, "Success!", Toast.LENGTH_SHORT).show();
System.out.println("popopopopopopopopopopo");
sessionManager.createSession(name, email, id, photo);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error "+ e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error "+ error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("photo",photo);
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void chooseFile(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
UploadPicture(getId, getStringImage(bitmap));
}
}
private void UploadPicture(final String id, final String photo) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(HomeActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Try Again!"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Try Again!" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id", id);
params.put("photo", photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
System.out.println("encodedImage " + encodedImage);
return encodedImage;
}
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
/>
<Button
android:id="#+id/btn_photo"
style="#style/Widget.AppCompat.ActionButton.CloseMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/photo"
android:layout_centerHorizontal="true"
android:text="Edit Photo" />
<LinearLayout
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="#id/btn_photo"
android:weightSum="2"
android:id="#+id/layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:src="#drawable/ic_name"
android:layout_weight="1"
android:layout_width="70dp"
android:layout_height="50dp" />
<EditText
android:id="#+id/name"
android:hint="Name"
android:inputType="textPersonName"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="#id/layout_text"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:src="#drawable/ic_email"
android:layout_weight="1"
android:layout_width="70dp"
android:layout_height="50dp" />
<EditText
android:id="#+id/email"
android:hint="Email"
android:inputType="textPersonName"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:layout_alignParentBottom="true"
android:id="#+id/btn_logout"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginBottom="30dp"
android:textColor="#android:color/white"
android:backgroundTint="#color/colorPrimary"
android:text="Logout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Please any one can help me in details.
I used android studio and xamp server.
The table contain: id, name, email,password, photo(path)
In the onActivityResult event, you already get the image URI. Use the setImageURI method.
Uri filePath = data.getData();
imageView.setImageURI(uri);
i use volley library on android code
i want to know check if my table has been updated or inserted then wanted to do it(A), otherwise it(B)
for example if my table updated or inserted then send (A)sms otherwise (B)toast
its my activity code:
public class DeviceAddActivity extends AppCompatActivity implements View.OnClickListener {
private static final String REGISTER_URL = "http://192.168.43.190/entezam/addphone.php";
public static final String KEY_CUSTNAME = "Customer_non";
public static final String KEY_PHONENAME = "Phone_Name";
public static final String KEY_IMEI = "IMEI";
private EditText editTextName;
private EditText editTextPhoneName;
private EditText editTextIMEI;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_add);
editTextName = (EditText) findViewById(R.id.editTextcustname);
editTextPhoneName = (EditText) findViewById(R.id.editTextphonename);
editTextIMEI= (EditText) findViewById(R.id.editTextimei);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
private void registerUser(){
final String Customer_non = editTextName.getText().toString().trim();
final String Phone_Name = editTextPhoneName.getText().toString().trim();
final String IMEI = editTextIMEI.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(DeviceAddActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceAddActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_CUSTNAME,Customer_non);
params.put(KEY_PHONENAME,Phone_Name);
params.put(KEY_IMEI,IMEI);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
}
and its my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Phone_Name = $_POST['Phone_Name'];
$Customer = $_POST['Customer_non'];
$IMEI = $_POST['IMEI'];
require_once('dbConnect.php');
$sql = "INSERT INTO phone_in (Phone_Name,Customer_non,IMEI) VALUES ('$Phone_Name','$Customer','$IMEI')";
if(mysqli_query($con,$sql)){
echo "Successfully Registered";
}else{
echo "Could not register";
}
}else{echo 'error';}
I'm trying to add a progress dialog to my app whilst it loads data from a volley. I've tried a few ways but i'm currently following this tutorial http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/ and was hoping it would look like the example used there. Please could someone take a look at my code so far! i'm not getting errors but it is not displaying like the example. As you can see i've created the method in onCreate and called the hide method in my response listeners.
Thank you!
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
LinearLayout layout;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading Articles...");
pDialog.show();
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
private SearchView.OnQueryTextListener searchQueryListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, SearchResultsActivity.class);
searchIntent.putExtra("query", query);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
hidePDialog();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
hidePDialog();
}
};
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/newsListItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<GridView
android:id="#+id/newsFeedList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Try Below Code
ProgressDialog pd = ProgressDialog.show(context,null,"Please wait");
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if(pd!=null && pd.isShowing())
pd.dismiss();
// Code
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(pd!=null && pd.isShowing())
pd.dismiss();
// Code
});
app.requestQueue.add(jsonRequest);
Try this:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
By the way, you should have an introduction with AsyncTask and should display ProgressDialog in that task.
private ProgressBarCircularIndetermininate pBar;
pBar = (ProgressBarCircularIndetermininate) getView().findViewById(R.id.progressBarCircularIndetermininate);
private void makeJsonRequest() {
showProgressDialog();
StringRequest strReq = new StringRequest(Method.POST, URL.DASHBOARD, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
} catch (JSONException e) {
e.printStackTrace();
}
}
hideProgressDialog();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
AppController.getInstance().volleyErrorHandler(error);
hideProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userID);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, NUMOFATTEMPT, BACKOFMULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showProgressDialog() {
if (!pBar.isShown())
pBar.setVisibility(View.VISIBLE);
}
private void hideProgressDialog() {
if (pBar.isShown())
pBar.setVisibility(View.GONE);
}
I know I am late for this topic(5 years, 5 months late), but this might help future readers. It's quite easy to do this. Just create a Progress Dialog first before creating the StringRequest from volley.
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Set Title");
progressDialog.setMessage("Set A Message");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// There are 3 styles, You'll figure it out :)
progressDialog.setCancelable(false);
progressDialog.setIcon(R.drawable.open_food_facts_symbol);
Then after creating the String request, override the onRespose method and DISMISS the progress dialog there.(You'll be showing the Progress Dialog when you add the request to the request queue)
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
progressDialog.dismiss();
}
});
Or this will be the same when using Lamda expressions like this,
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response ->
{
progressDialog.dismiss();
});
Then after adding the ErrorListeners and the user agents, show the Progress Dialog after adding the StringRequest to the queue.
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
progressDialog.show();
That's it. All done. Here's the full code.
private void parseApiData(String productBarcode)
{
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Connecting To the Database");
progressDialog.setMessage("We are not establishing a Connection to the Open Food Facts Database...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setIcon(R.drawable.open_food_facts_symbol);
//progressDialog.
String url = "this will be your url..";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response ->
{
progressDialog.dismiss();
}
} catch (JSONException e) {
progressDialog.dismiss();
e.printStackTrace();
} catch (Exception e) {
progressDialog.dismiss();
statusCode = 0;
}
}, volleyError -> {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError)
{
Toast.makeText(context, "Connection Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof AuthFailureError)
{
Toast.makeText(context, "Authentication/ Auth Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof ServerError)
{
Toast.makeText(context, "Server Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof NetworkError)
{
Toast.makeText(context, "Network Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof ParseError)
{
Toast.makeText(context, "Parse Error !", Toast.LENGTH_LONG).show();
}
activity.finish();
})
{
//Assigning the User Agent
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("User-Agent:", "Your custom user agent here");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
progressDialog.show();
}