I am unable to save data from Android webview in mysql database - java

I am accessing https://curj.000webhostapp.com/pmei_alumni/alumni_form.php through Android webview. I want to Save the form data into Mysql database. The problem is that by pressing the Save button it does not responded. It does not save the data into mysql.
Following is the code. Please help ..
Your Response would be Appreciable....
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bilalkhawaja.pmeialumni.MainActivity">
<im.delight.android.webview.AdvancedWebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Here is the ManinActivity.JAVA Code
package com.example.bilalkhawaja.pmeialumni;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import im.delight.android.webview.AdvancedWebView;
public class MainActivity extends AppCompatActivity implements
AdvancedWebView.Listener {
String Url =
"https://curj.000webhostapp.com/pmei_alumni/pmei_alumni.php";
public AdvancedWebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (AdvancedWebView) this.findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(Url);
mWebView.setListener(this,this);
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
super.onResume();
mWebView.onResume();
// ...
}
#SuppressLint("NewApi")
#Override
protected void onPause() {
mWebView.onPause();
// ...
super.onPause();
}
#Override
protected void onDestroy() {
mWebView.onDestroy();
// ...
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
intent) {
super.onActivityResult(requestCode, resultCode, intent);
mWebView.onActivityResult(requestCode, resultCode, intent);
// ...
}
#Override
public void onBackPressed() {
if (!mWebView.onBackPressed()) { return; }
// ...
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
}
#Override
public void onPageError(int errorCode, String description, String
failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename,
String mimeType, long contentLength, String contentDisposition, String
userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
**AndroidManifest.xml code**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bilalkhawaja.pmeialumni">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Html Form From which i am saving data into mysql database using Android Webview

Related

How to code Enable and Disable Wifi, Mobile Data and GPS by one same switch?

How to code Enable and Disable Wifi, Mobile Data and GPS by one same switch in android studio ?
I've found a code that only enable and disable wifi by switch. But I'm looking for a code of android studio that enable and disable Wifi, Mobile Data and GPS by one same switch in the same time.
package com.pc.ibms.helptechattendancescanner;
import androidx.appcompat.app.AppCompatActivity;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
public class MainActivity extends AppCompatActivity {
Switch aSwitch;
WifiManager wifiManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aSwitch=(Switch)findViewById(R.id.myswitch);
wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
//register the switch for event handling
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked && !wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
//to switch off wifi
else if(!isChecked && wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
}
}
});
}
}
Main Activity
package com.pc.ibms.helptechattendancescanner;
import androidx.appcompat.app.AppCompatActivity;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
public class MainActivity extends AppCompatActivity {
Switch aSwitch;
WifiManager wifiManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aSwitch=(Switch)findViewById(R.id.myswitch);
wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
//register the switch for event handling
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked && !wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
//to switch off wifi
else if(!isChecked && wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
}
}
});
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pc.ibms.helptechattendancescanner">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/App_Name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
**Activity Main**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myswitch"
android:text="WiFi Setting"
android:textOn="ON"
android:textOff="OFF"
android:showText="true"
/>
</RelativeLayout>

Can't display list of wifi connected devices in Android

I have issue with this code.I am trying to display all devices that are connected on the same WIFI in the list.
I did debugging and it shows that connection with WIFI was made but it does not detect any devices, even though there are some connected devices for sure. I did pinging with both sides with computer and android and connection was made.
If you guys have any ideas where could be a problem, please let me know, cause I am out of ideas.
MANIFEST FILE.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:required="true" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.NFC"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".Intro_Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_intro_"
android:theme="#style/FullscreenTheme"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Activity_Main.xml
<?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"
android:orientation="vertical"
tools:context="com.example.app.MainActivity">
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onToggleClicked"
android:textOff="Wi-Fi Off"
android:textOn="Wi-Fi On" />
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MainActivity.java
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private WifiManager wifiManager;
private BroadcastReceiver wifiReciever;
private ArrayAdapter adapter;
SupplicantState supState;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WiFiScanReceiver();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
}
public void onToggleClicked(View view) {
adapter.clear();
ToggleButton button = findViewById(R.id.toggleButton);
if (wifiManager == null) {
//device does not support wifi
Toast.makeText(getApplicationContext(), "Oop! Your device does not support Wi-Fi",
Toast.LENGTH_SHORT).show();
button.setChecked(false);
} else {
if (button.isChecked()) { // to turn on wifi
if (!wifiManager.isWifiEnabled()) {
Toast.makeText(getApplicationContext(), "Wi-Fi is turned on." +
"\n" + "Scanning for access points...",
Toast.LENGTH_SHORT).show();
wifiManager.setWifiEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "Wi-Fi is already turned on." +
"\n" + "Scanning for access points...",
Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
} else {
Toast.makeText(getApplicationContext(), "Wi-Fi is turned off.",
Toast.LENGTH_SHORT).show();
}
}
}
class WiFiScanReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
List<ScanResult> wifiScanResultList = wifiManager.getScanResults();
for (int i = 0; i < wifiScanResultList.size(); i++) {
ScanResult accessPoint = wifiScanResultList.get(i);
String listItem = accessPoint.SSID + ", " + accessPoint.BSSID;
adapter.add(listItem);
}
}
}
}
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReciever, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiReciever);
}
}

Open specific links in browser, instead of webview by regex

I'm using parts of code form some tutorial to create webview app. Goals is - to open links, that not contain appdev365 in browser, not in webview. I am completly noob at android development, so all that i've searched - didn't match to my(from tutorial) code.
MainActivity.java
package com.example.ynt;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://yatln.com/appdev365/index.php");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ynt">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Y&T База талантов"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ynt.MainActivity">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible" />
</RelativeLayout>
SOLUTION (by Varma Lanke):
https://gist.github.com/codedamage/8f98e2ed13d1d1fa05e5d43e67ea3e6c
private WebView htmlWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
htmlWebView = (WebView)findViewById(R.id.webview);
htmlWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.loadUrl("https://yatln.com/appdev365/index.php");
}
private class CustomWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("appdev365"))
view.loadUrl(url);
else{
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
// view.loadUrl(url);
return true;
}
}
For you should use shouldOverrideUrlLoading method, once try the below one
private WebView htmlWebView;
String url = "https://yatln.com/appdev365/index.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
htmlWebView = (WebView)findViewById(R.id.webView);
if(url.contains("appdev365"))
htmlWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.loadUrl(url);
}
private class CustomWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equalsIgnoreCase("appdev365"))
view.loadUrl(url);
return true;
}
}
This code opens browser and specified link (ex. google.com):
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

Location Listener onLocationChange () method not working

My Android Phone model # is Sony Z3 Compact Japanese (SO-O2G)
Google Maps and all other apps related to location Works fine on my device
But i want to develop my own location-based application and on First step of developing my code is not working.. I don't know what is the problem in my Code. onLocationChange () method not triggered.. Even not finding my current location
Manifest Code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testingpurpose">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
<uses-feature android:name="android.hardware.location.network"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.testingpurpose;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private Location lastLocation;
private double distanceIntoMeters;
private final String PERMISSION_ONE = Manifest.permission.ACCESS_FINE_LOCATION;
private final String PERMISSION_TWO = Manifest.permission.ACCESS_COARSE_LOCATION;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this,PERMISSION_ONE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this,PERMISSION_TWO ) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{PERMISSION_ONE, PERMISSION_TWO}, 0);
}
}
#Override
protected void onStart() {
super.onStart();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if ( locationManager != null ){
if (ContextCompat.checkSelfPermission(this,PERMISSION_ONE) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this,PERMISSION_TWO ) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
else{
Toast.makeText(this,"Permission not Granted",Toast.LENGTH_SHORT).show();
}
periodicallyCheck();
}
void periodicallyCheck(){
final Handler handler = new Handler();
final TextView tv = findViewById(R.id.tv);
handler.post(new Runnable() {
#Override
public void run() {
String format = String.format("%.2f %s",distanceIntoMeters,"meters");
tv.setText(format);
handler.postDelayed(this,1000);
}
});
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if ( lastLocation == null ){
lastLocation = location;
}
Log.i("Location Updates: ",">>> Lat "+location.getLatitude()+" , >>> Long "+location.getLongitude());
distanceIntoMeters = distanceIntoMeters + location.distanceTo(lastLocation);
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
#Override
protected void onDestroy() {
super.onDestroy();
if (locationManager != null && listener != null){
locationManager.removeUpdates(listener);
}
}
}
activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

An android application that chooses photo from gallery and uploads into the firebase batabase

Like I said in my title I am trying to learn to use databases in android application. So I thought of creating a sample application that takes photos from gallery and uploads the image into the firebase database. However, my application collapses itself after I select a photo from gallery.
Here is my android manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.trump.demo_cameraapp">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
Here is my layout file, activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width = "match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="2">
</ImageView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Photo!"
android:textColor="#color/Blue"
android:id="#+id/chooseButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Upload Photo!"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/uploadButton"/>
</LinearLayout>
I have the following lines of code in MainActivity
package com.example.trump.demo_cameraapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PICK_IMAGE_REQUEST = 1;
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
private ImageView mImageView;
private StorageReference storage;
private ProgressDialog mProgressDialog;
public static final int GALLERY_INTENT = 2;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
mImageView = (ImageView) findViewById(R.id.imageView1);
Button choose = (Button) findViewById(R.id.chooseButton);
choose.setOnClickListener(this);
Button upload = (Button) findViewById(R.id.uploadButton);
upload.setOnClickListener(this);
}
private void showFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select an image"),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) {
Log.d("ResultOK", String.valueOf(RESULT_OK));
Log.d("CameraDemo", "Pic saved");
mProgressDialog.setMessage("Uploading...");
mProgressDialog.show();
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
mImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
StorageReference filepath = storage.child("images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>(){
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.chooseButton){
showFileChooser();
}else if(view.getId() == R.id.uploadButton){
}
}
}
I have not yet written codes to upload the image on firebase database. All I am trying to do right now is to display the image I picked from gallery in the imageview of my app. However, like I said before it's not displaying anything right now and as soon as I choose some photo from gallery it collapses. Any help regarding the issue would be very appreciated.
I think there is no issue with your image picker code, what i found a problem is that you are using mProgressDialog without initializing it in the onCreate() method. So what is recommend is that you first initialize mProgressDialog object in your onCreate() method right after you the initialization of mImageView. And i hope that your application will not collapse now.

Categories