Android application crashes at setContentView at OnCreate only on low android API - java

My application works at API 24 and above but crashes at API 19.
the problem seem to be at setContentView line in the OnCreate method.
I tried to change all API 21+ features at android XML file but it didn't help.
Also tried to put multidex and it didn't work.
I added here
the setContentView method:
package com.idan.idanzimbler.epiclogin.view;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.idan.idanzimbler.epiclogin.R;
import com.idan.idanzimbler.epiclogin.controller.FillSeriesListFromFireBaseBySearchTask;
import com.idan.idanzimbler.epiclogin.controller.FillSeriesListFromFireBaseBySuggestionsTask;
import com.idan.idanzimbler.epiclogin.controller.FillSeriesListFromFireBaseTask;
import com.idan.idanzimbler.epiclogin.controller.TvSeriesFavoriteList;
import com.idan.idanzimbler.epiclogin.controller.TvSeriesHomeList;
import com.idan.idanzimbler.epiclogin.controller.UsersBookmarks;
import com.idan.idanzimbler.epiclogin.modle.TvSeries;
import com.google.firebase.auth.FirebaseAuth;
import com.squareup.picasso.Picasso;
import java.util.Locale;
public class HomeActivity extends AppCompatActivity implements AbsListView.OnScrollListener {
public static final String INTENT_FLAG = "flag";
public static final int FIRST_ENTER = 1;
//public static final int REBUILD = 2;
public static final int RECOMMENDATION_ENTER = 2;
ExpandableListView list;
EditText searchEt;
ProgressBar progressBar;
HomeActivity context;
ImageView questionmarkHomeBtn;
boolean isInSearchMode;
boolean isInRecommendationMode;
TextView homeToolbarTitleTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
loadLocale();
Toolbar toolbar = findViewById(R.id.homeToolbar);
toolbar.setTitle("");
homeToolbarTitleTV = findViewById(R.id.home_titleTV);
setSupportActionBar(toolbar);
context = this;
isInSearchMode = false;
isInRecommendationMode = false;
progressBar = findViewById(R.id.home_progressbar);
questionmarkHomeBtn = findViewById(R.id.home_questionmark_btn);
list = findViewById(R.id.home_series_list);
searchEt = findViewById(R.id.home_search_et);
progressBar.setVisibility(View.VISIBLE);
TvSeriesHomeList.getInstance().clear();
TvSeriesFavoriteList.getInstance().clear();
TvSeriesFavoriteList.getInstance().initializeSeriesList();
UsersBookmarks.getInstance().initializeBookmarks();
Bundle b = getIntent().getExtras();
int flag = 1;
if (b != null) flag = b.getInt(INTENT_FLAG);
if (flag == FIRST_ENTER) {
new FillSeriesListFromFireBaseTask(this, list).execute();
} else if (flag == RECOMMENDATION_ENTER) {
progressBar.setVisibility(View.VISIBLE);
isInRecommendationMode = true;
homeToolbarTitleTV.setText(getString(R.string.recommendation));
new FillSeriesListFromFireBaseBySuggestionsTask(context, list).execute();
}
list.setOnScrollListener(this);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TvSeriesFavoriteList favorites = TvSeriesFavoriteList.getInstance();
TvSeries series = TvSeriesHomeList.getInstance().getSeries().get(position);
if (favorites.contains(series.getId())) {
favorites.remove(series.getId());
ImageView star = view.findViewById(R.id.series_list_fav_iv);
Picasso.get().load(R.drawable.emptystar).fit().into(star);
Toast.makeText(getApplicationContext(), "Removed from favorites", Toast.LENGTH_SHORT).show();
} else if (favorites.canAdd(series)) {
favorites.add(series);
ImageView star = view.findViewById(R.id.series_list_fav_iv);
Picasso.get().load(R.drawable.filledstar).fit().into(star);
Toast.makeText(getApplicationContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Maximum of 5 series can be added to favorites", Toast.LENGTH_SHORT).show();
}
return true;
}
});
searchEt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String searchString = s.toString().trim();
if (searchString.isEmpty()) {
isInSearchMode = false;
TvSeriesHomeList.getInstance().clear();
new FillSeriesListFromFireBaseTask(context, list).execute();
} else {
isInSearchMode = true;
new FillSeriesListFromFireBaseBySearchTask(context, list, searchString).execute();
}
}
});
questionmarkHomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setCancelable(true);
builder.setTitle(getString(R.string.how_to_use));
builder.setMessage(getString(R.string.home_fav_bookmark_explain));
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
});
}
#Override
protected void onResume() {
super.onResume();
loadLocale();
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!isInSearchMode && !isInRecommendationMode) {
switch (view.getId()) {
case R.id.home_series_list:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (TvSeriesHomeList.getInstance().getPreLast() != lastItem) {
TvSeriesHomeList.getInstance().incrementPage();
new FillSeriesListFromFireBaseTask(this, list).execute();
TvSeriesHomeList.getInstance().setPreLast(lastItem);
}
}
}
}
}
public ProgressBar getProgressBar() {
return progressBar;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.profilemenu:
startActivity(new Intent(this, ProfileActivity.class));
break;
case R.id.favoritesmenu:
startActivity(new Intent(this, FavoritesActivity.class));
break;
case R.id.aboutmenu:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.signoutmenu:
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.recommendationmenu:
TvSeriesHomeList.getInstance().clear();
progressBar.setVisibility(View.VISIBLE);
isInRecommendationMode = true;
new FillSeriesListFromFireBaseBySuggestionsTask(context, list).execute();
homeToolbarTitleTV.setText(getString(R.string.recommendation));
break;
case R.id.homemenu:
if (isInRecommendationMode) {
isInRecommendationMode = false;
TvSeriesHomeList.getInstance().clear();
new FillSeriesListFromFireBaseTask(this, list).execute();
}
homeToolbarTitleTV.setText(getString(R.string.home));
break;
case R.id.rateusmenu:
try{
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.idan.idanzimbler.epiclogin")));
}catch (ActivityNotFoundException e){
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.idan.idanzimbler.epiclogin")));
}
}
return true;
}
#Override
public void onBackPressed() {
if (!searchEt.getText().toString().isEmpty()) {
searchEt.setText("");
} else if (isInRecommendationMode) {
isInRecommendationMode = false;
TvSeriesHomeList.getInstance().clear();
new FillSeriesListFromFireBaseTask(this, list).execute();
}else {
super.onBackPressed();
}
}
public void setLocale(String lang) {
Locale locale = new Locale(lang,"US");
if(lang.equals("he")){
locale = new Locale(lang,"IL");
}
else if(lang.equals("ar")){
locale = new Locale(lang,"JO");
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences("Settings" ,MODE_PRIVATE).edit();
editor.putString("My_Lang",lang);
editor.apply();
}
public void loadLocale(){
SharedPreferences prefs = getSharedPreferences("Settings",Activity.MODE_PRIVATE);
String language = prefs.getString("My_Lang", "");
setLocale(language);
}
}
The XML file:
<?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=".view.HomeActivity">
<EditText
android:id="#+id/home_search_et"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="14dp"
android:layout_weight="1"
android:ems="10"
android:hint="#string/enter_tv_series_name"
android:inputType="textPersonName"
app:backgroundTint="#color/common_google_signin_btn_text_dark_focused"
app:layout_constraintBottom_toTopOf="#+id/home_series_list"
app:layout_constraintEnd_toStartOf="#+id/home_questionmark_btn"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout"
/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_constraintBottom_toTopOf="#+id/home_search_et"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.Toolbar
android:id="#+id/homeToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"
android:contentInsetEnd="0dp"
android:contentInsetRight="0dp"
android:elevation="2dp"
android:gravity="end"
app:contentInsetEnd="0dp"
app:contentInsetLeft="0dp"
app:contentInsetRight="0dp"
app:contentInsetStart="0dp"
app:popupTheme="#style/AppTheme.PopupOverlay"
tools:targetApi="lollipop">
<TextView
android:id="#+id/home_titleTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/home"
android:textColor="#color/common_google_signin_btn_text_dark_default"
android:textSize="25sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ExpandableListView
android:id="#+id/home_series_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="4dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/home_search_et" />
<ProgressBar
android:id="#+id/home_progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminateDrawable="#drawable/blackprogressbar"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="#+id/home_series_list"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/home_questionmark_btn"
android:layout_width="34dp"
android:layout_height="24dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="#+id/home_search_et"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/home_search_et"
app:srcCompat="#drawable/questionmarklogo"
android:contentDescription="TODO" />
</android.support.constraint.ConstraintLayout>
the Run:
V/FA: Activity paused, time: 2504321
V/FA: onActivityCreated
D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=11068, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-8684354233398184439}]
W/dalvikvm: JNI WARNING: NewStringUTF input is not valid Modified UTF-8: illegal start byte 0xf0
string: 'en_Latn_US_�_US'
in Llibcore/icu/ICU;.addLikelySubtags:(Ljava/lang/String;)Ljava/lang/String; (NewStringUTF)
I/dalvikvm: "main" prio=5 tid=1 NATIVE
| group="main" sCount=0 dsCount=0 obj=0xa4d56bd8 self=0xb7e34eb0
| sysTid=3387 nice=0 sched=0/0 cgrp=apps handle=-1216573376
| state=R schedstat=( 1431490769 212065377 2672 ) utm=91 stm=51 core=1
I/dalvikvm: #00 pc 000bd936 /system/lib/libdvm.so (dvmDumpNativeStack(DebugOutputTarget const*, int)+86)
#01 pc 00098513 /system/lib/libdvm.so (dvmDumpThreadEx(DebugOutputTarget const*, Thread*, bool)+1155)
#02 pc 00098806 /system/lib/libdvm.so (dvmDumpThread(Thread*, bool)+86)
#03 pc 0004d3ff /system/lib/libdvm.so (ScopedCheck::checkUtfString(char const*, bool)+271)
#04 pc 0004e2ad /system/lib/libdvm.so (ScopedCheck::check(bool, char const*, ...)+1437)
#05 pc 00052927 /system/lib/libdvm.so
#06 pc 000204be /system/lib/libjavacore.so
#07 pc 0002a4ab /system/lib/libdvm.so (dvmPlatformInvoke+79)
at libcore.icu.ICU.addLikelySubtags(Native Method)
I/dalvikvm: at android.text.TextUtils.getLayoutDirectionFromLocale(TextUtils.java:1740)
at android.content.res.Configuration.setLayoutDirection(Configuration.java:1295)
at android.content.res.Configuration.updateFrom(Configuration.java:820)
at android.content.res.Resources.updateConfiguration(Resources.java:1557)
at android.content.res.Resources.updateConfiguration(Resources.java:1511)
at android.support.v7.widget.ResourcesWrapper.updateConfiguration(ResourcesWrapper.java:232)
at android.content.res.Resources.<init>(Resources.java:202)
at android.content.res.Resources.<init>(Resources.java:179)
at android.support.v7.widget.ResourcesWrapper.<init>(ResourcesWrapper.java:48)
at android.support.v7.widget.TintResources.<init>(TintResources.java:35)
at android.support.v7.widget.TintContextWrapper.<init>(TintContextWrapper.java:101)
at android.support.v7.widget.TintContextWrapper.wrap(TintContextWrapper.java:69)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:69)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:65)
at android.support.v7.app.AppCompatViewInflater.createEditText(AppCompatViewInflater.java:192)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:114)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.idan.idanzimbler.epiclogin.view.HomeActivity.onCreate(HomeActivity.java:58)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
E/dalvikvm: VM aborting
A/libc: Fatal signal 6 (SIGABRT) at 0x00000d3b (code=-6), thread 3387 (mbler.
Application terminated.

The stacktrace seems to indicate an issue reading the current Resources Configuration (whether your Locale is RTL or not).
Looking at the activity code, you are modifying the Locale used by your application instead of using the phone Locale which would explain the issue. Your Activity will actually go through onCreate twice. The first time is probably inflating your XML view without any trouble but once you set the new Configuration (by calling loadLocale()), the Activity will be destroyed and re-created, which will execute onCreate() a second time with your new Configuration. This is when your application is crashing.
In my opinion, the problem is most likely in the setLocale() method, the change of Configuration is not done correctly and new APIs are able to use a default value whereas older APIs simply crash.
Even though I wouldn't recommend modifying the Locale in the app, here is more information on modifying it in an Android application:
https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758
There is different methods to use depending on the version of the APIs you support.
The method he is using to change the configuration looks like:
private static Context updateResources(Context context, Locale locale) {
Locale.setDefault(locale);
Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
context = context.createConfigurationContext(config);
} else {
config.locale = locale;
res.updateConfiguration(config, res.getDisplayMetrics());
}
return context;
}

Related

How to zoom out a bitmap image?

I'm capturing an image using a biometric reader.
Connecting the reader to the tablet and capturing the image works fine, but the image looks like this:
The image is cropped. It looks like it's magnified when the biometric capture takes place.
this is my code:
package mobfeel.com.br.exfingerprintreaderuareu4500;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import asia.kanopi.fingerscan.Status;
public class MainActivity extends AppCompatActivity {
private ImageView ivFingerprint;
private Button btScan;
private static final int SCAN_FINGERPRINT = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
btScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, SCAN_FINGERPRINT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case SCAN_FINGERPRINT:
if (resultCode == RESULT_OK) {
int status = data.getIntExtra("status", Status.ERROR);
if (status == Status.SUCCESS) {
toast("Fingerprint OK!");
byte[] img = data.getByteArrayExtra("img");
Bitmap bm = BitmapFactory.decodeByteArray(img, 0, img.length);
ivFingerprint.setImageBitmap(bm);
return;
}
toast(data.getStringExtra("errorMessage"));
}
break;
}
}
private void toast(String msg){
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
private void init(){
ivFingerprint = findViewById(R.id.ma_iv_fingerprint);
btScan = findViewById(R.id.ma_bt_scan);
}
}
And this is my activity_main.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">
<ImageView
android:id="#+id/ma_iv_fingerprint"
android:layout_width="221dp"
android:layout_height="206dp"
android:layout_gravity="center"
android:layout_marginBottom="460dp"
android:adjustViewBounds="true"
android:scaleType="fitXY"
app:layout_constraintBottom_toTopOf="#+id/ma_bt_scan"
app:srcCompat="#mipmap/ic_launcher"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="8dp" />
<Button
android:id="#+id/ma_bt_scan"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Scan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
I also have the ScanActivity.java class
package mobfeel.com.br.exfingerprintreaderuareu4500;
import android.content.Intent;
import android.os.Looper;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import asia.kanopi.fingerscan.Fingerprint;
import asia.kanopi.fingerscan.Status;
public class ScanActivity extends AppCompatActivity {
private TextView tvStatus;
private Fingerprint fingerprint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
init();
}
#Override
protected void onStart() {
fingerprint.scan(ScanActivity.this, printHandler, updateHandler);
super.onStart();
}
#Override
protected void onStop() {
fingerprint.turnOffReader();
super.onStop();
}
Handler updateHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
int status = msg.getData().getInt("status");
switch (status) {
case Status.INITIALISED:
tvStatus.setText("Setting up reader");
break;
case Status.SCANNER_POWERED_ON:
tvStatus.setText("Reader powered on");
break;
case Status.READY_TO_SCAN:
tvStatus.setText("Ready to scan finger");
break;
case Status.FINGER_DETECTED:
tvStatus.setText("Finger detected");
break;
case Status.RECEIVING_IMAGE:
tvStatus.setText("Receiving image");
break;
case Status.FINGER_LIFTED:
tvStatus.setText("Finger has been lifted off reader");
break;
case Status.SCANNER_POWERED_OFF:
tvStatus.setText("Reader is off");
break;
case Status.SUCCESS:
tvStatus.setText("Fingerprint successfully captured");
break;
case Status.ERROR:
tvStatus.setText("Error");
toast(msg.getData().getString("errorMessage"));
break;
default:
tvStatus.setText(String.valueOf(status));
toast(msg.getData().getString("errorMessage"));
break;
}
}
};
Handler printHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
byte[] image;
String errorMessage = "";
int status = msg.getData().getInt("status");
Intent intent = new Intent();
intent.putExtra("status", status);
if (status == Status.SUCCESS) {
intent.putExtra("img", msg.getData().getByteArray("img"));
} else {
intent.putExtra("errorMessage", msg.getData().getString("errorMessage"));
}
setResult(RESULT_OK, intent);
finish();
}
};
private void toast(String msg){
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
private void init() {
tvStatus = findViewById(R.id.sa_tv_status);
fingerprint = new Fingerprint();
}
}
activity_scan.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=".ScanActivity">
<TextView
android:id="#+id/sa_tv_status"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
What feature can I use to zoom out?
I appreciate if anyone can help me analyze this!

Sudden error about not resolving some methods and symbols

I'm a beginner programmer and I'm working on an app where I want to have a Settings activity with 2 switch buttons (one to turn on/off notifications in status bar and one to turn on/off notification sound).Yesterday everything went fine with the compiling but today suddenly I got all these errors about not resolving some methods or symbols. What happened and how can I fix it?
In particular the errors where the following:
cannot resolve method: onCreate,setContentView,getSystemService, findViewById
cannot resolve symbol: OnCheckedChangeListener, simpleswitch1, simpleswitch2, arg0, view
Override: Annotations are not allowed here
onClick and onCheckedChanged do not work properly.
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new View.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void onCheckedChanged(CompoundButton simpleswitch1, boolean isChecked) {
if (isChecked) {
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}});
public void onClick(View view) {
public void onCheckedChanged(CompoundButton simpleswitch2, boolean isChecked) {
if (isChecked){
notification.defaults |= Notification.DEFAULT_SOUND;
}}}}}
XML File
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>
From you java you are placing methods inside other methods this is not possible in java
Also
Try setting listeners as such
// set default state on/off
simpleSwitch1.setChecked(false);
simpleSwitch2.setChecked(false);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
simpleSwitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
hope this helps, your java code was quite hard to understand.

Android: Calculate price from clicked items in listview. App crashes in total activity Logcat:Invalid float: ""

Im a noob in this so please bear with me. I have a listview of food and drinks with price then a proceed button which will show the order summary and total amount in other activity. After I click some items then click the proceed button, the app crash "Unfortunately appname has stopped." But when I click proceed button without clicking any items it displays the layout of the order summary. Therefore the error occurs in the passing of data. In logcat I noticed first Invalid float: "" I have no idea how to fix this.
I used SQLite for database of items
This is the code of activity for order summary and total amount where the error seems to appear.
package edu.sti.snapchit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.StringTokenizer;
import java.lang.String;
public class TotalsActivity extends AppCompatActivity{
MyApp mApp;
EditText et_summary;
TextView tv_total;
Button btn_code;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.totals);
btn_code = (Button) findViewById(R.id.btn_code);
mApp=((MyApp)getApplicationContext());
et_summary = (EditText) findViewById(R.id.et_summary);
tv_total = (TextView) findViewById(R.id.tv_total);
et_summary.setText(mApp.getGlobalVarValue());
String str = mApp.getGlobalVarValue();
StringTokenizer st = new StringTokenizer(str,"Php");
String test="";
float total=0;
int count =0;
while(st.hasMoreElements())
{
test = st.nextElement().toString().substring(0,1);
if(count>0)
total += Float.parseFloat(test);
count++;
}
tv_total.setText("Total:" + total+"");
mApp.setGlobalClear();
btn_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(TotalsActivity.this, GeneratorActivity.class);
startActivity(intent);
}
});
}
public boolean isFloat(String input)
{
try
{
Float.parseFloat(input);
return true;
}
catch(Exception e)
{
return false;
}
}
}
Total XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:weightSum="1"
android:background="#android:color/holo_orange_light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Order Summary "
android:textSize="30dp"
android:id="#+id/textV"
android:layout_gravity="center_horizontal"
android:layout_weight="0.07"
android:background="#android:color/holo_blue_dark"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#android:color/background_light"
android:layout_marginTop="6dp">
<EditText
android:id="#+id/et_summary"
android:layout_width="match_parent"
android:layout_height="267dp"
android:layout_gravity="center_horizontal"
android:layout_weight="0.55"
android:inputType="text"
android:textSize="24dp"
android:hint="Summary"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total : "
android:textSize="30dp"
android:layout_weight="0.07"
android:id="#+id/tv_total"/>
</LinearLayout>
<Button
android:id="#+id/btn_code"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:background="#drawable/buttonborder"
android:clickable="true"
android:text="Proceed to Qr Code Generator"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
</LinearLayout>
Code for Food Activity which contains the listview
package edu.sti.snapchit;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.HashMap;
public class NewFoodsActivity extends AppCompatActivity {
MyApp mApp;
private HashMap<String, Location> locations;
ListView listView1;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db=openOrCreateDatabase("Foods_DB", Context.MODE_PRIVATE, null);
setContentView(R.layout.new_foods);
locations = loadLocationData();
addListenerButton();
initializeUI();
}
public void initializeUI()
{
String[] foodies = getFoodNames();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1, foodies);
listView1.setAdapter(adapter);
}
private String[] getFoodNames()
{
String[] foodies = new String[locations.size()];
foodies = locations.keySet().toArray(foodies);
return foodies;
}
private void displaySelectedFoodInfo(String foodName)
{
}
public void showMessage(String title,String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
private HashMap<String, Location>loadLocationData()
{
HashMap<String, Location>locations = new HashMap<String, Location>();
Cursor c=db.rawQuery("SELECT * FROM table_foods order by food_id
asc",null);
StringBuffer buffer = new StringBuffer();
while(c.moveToNext())
{
locations.put("- "+c.getString(1).toString()+" [Php
"+c.getString(2).toString()+"]", new Location(Integer.parseInt(c.getString(0)),c.getString(1).toString(),Double.parseDouble(c.getString(2))));
}
return locations;
}
public void addListenerButton()
{
final Context context = this;
Button btnAdd = (Button)findViewById(R.id.btn_add);
Button btnProceed = (Button)findViewById(R.id.btnProceed);
Button btn_drinks = (Button)findViewById(R.id.btn_drinks);
Button btn_foods = (Button)findViewById(R.id.btn_foods);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> Arg0, View view, int
position, long id) {
Object o = listView1.getItemAtPosition(position);
String pen = o.toString();
mApp=((MyApp)getApplicationContext());
mApp.setGlobalVarValue(pen);
Toast.makeText(getApplicationContext(), "Item Added" +
""+ pen, Toast.LENGTH_LONG).show();
}
}
);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, NewAddFoods.class);
startActivity(intent);
}
});
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, TotalsActivity.class);
startActivity(intent);
}
});
btn_foods.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, NewFoodsActivity.class);
startActivity(intent);
}
});
btn_drinks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, NewDrinksActivity.class);
startActivity(intent);
}
});
}
}
Food XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:gravity="bottom|center_horizontal"
android:orientation="vertical"
android:background="#android:color/holo_orange_light">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Food Items"
android:textAlignment="center"
android:textSize="30sp"
android:background="#android:color/holo_blue_dark"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<Button
android:id="#+id/btn_foods"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:text="Foods"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<Button
android:id="#+id/btn_drinks"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:text="Drinks"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="350dp"
android:id="#+id/listView1"
android:background="#android:color/background_light"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp"
>
<Button
android:id="#+id/btn_add"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Add Snacks"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<Button
android:id="#+id/btnProceed"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Proceed"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
</LinearLayout>
MyApp
package edu.sti.snapchit;
import android.app.Application;
public class MyApp extends Application{
private String mGlobalVarValue="";
public String getGlobalVarValue(){
return mGlobalVarValue;
}
public void setGlobalVarValue(String str){
mGlobalVarValue += str+"\n";
}
public void setGlobalClear(){
mGlobalVarValue="";
}
}
Location
package edu.sti.snapchit;
public class Location {
private int id;
private String name;
private double price;
public Location(int id,String name, double price){
this.id = id;
this.name = name;
this.price = price;
}
#Override
public String toString(){
return this.id + " " +this.name +" " +this.price;
}
}
This is the colored red text in LOGCAT
02-20 04:37:23.624 1447-1447/edu.sti.snapchit E/AndroidRuntime: FATAL
EXCEPTION: main
java.lang.RuntimeException: Unable to start activity
ComponentInfo{edu.sti.snapchit/edu.sti.snapchit.TotalsActivity}:
java.lang.NumberFormatException: Invalid float: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:289)
at java.lang.Float.parseFloat(Float.java:300)
at edu.sti.snapchit.TotalsActivity.onCreate(TotalsActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-20 04:37:29.372 1494-1494/edu.sti.snapchit E/dalvikvm: Could not
find class 'android.graphics.drawable.RippleDrawable', referenced from
method
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-20 04:37:30.592 1494-1494/edu.sti.snapchit E/OpenGLRenderer:
Getting MAX_TEXTURE_SIZE from GradienCache 02-20 04:37:30.616
1494-1494/edu.sti.snapchit E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE
from Caches::initConstraints()
Ps. Yes I did followed a youtube tutorial in making this app. The app in vid is working perfectly while mine crashes. Either I missed something but I checked the code like 10 times or either there are parts of the vid been skipped. The uploader havent respond for days :(
I almost forgot there might also another reason that caused this. In TotalsActivity the method isFloat is never used.
enter image description here
If you've read error log carefully then it would be easy. Anyways. just replace below code
package edu.sti.snapchit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.StringTokenizer;
import java.lang.String;
public class TotalsActivity extends AppCompatActivity{
MyApp mApp;
EditText et_summary;
TextView tv_total;
Button btn_code;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.totals);
btn_code = (Button) findViewById(R.id.btn_code);
mApp=((MyApp)getApplicationContext());
et_summary = (EditText) findViewById(R.id.et_summary);
tv_total = (TextView) findViewById(R.id.tv_total);
et_summary.setText(mApp.getGlobalVarValue());
String str = mApp.getGlobalVarValue();
StringTokenizer st = new StringTokenizer(str,"Php");
String test="";
float total=0;
int count =0;
while(st.hasMoreElements())
{
test = st.nextElement().toString().substring(0,1);
if(count>0 && test !=null && !test.isEmpty()){
total += Float.parseFloat(test);
}
count++;
}
tv_total.setText("Total:" + total+"");
mApp.setGlobalClear();
btn_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(TotalsActivity.this, GeneratorActivity.class);
startActivity(intent);
}
});
}
public boolean isFloat(String input)
{
if(input.isEmpty() || input == null)
return false;
try
{
Float.parseFloat(input);
return true;
}
catch(Exception e)
{
return false;
}
}
}

App seems like launching more than once in landscape mode after splash screen?

I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
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"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.

Application crashed on Button click saying attempt to invoke virtual method 'void android.widget.Button.setOnClickListener'

This code gives me error while I click on Upload Photo Button of activity_home.xml. This Application was working fine until I didn't added Upload Activity. Upload Activity is all about pushing a picture to ftp server. The Upload Activity works fine as a standalone apk. This error shows when I joined these two separate apks with created an intent b/w the two separate views.
I am not sure does the application crash on button click.
Log Exception
Process: com.muchmore.www.chasquido, PID: 9571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.muchmore.www.chasquido/com.muchmore.www.chasquido.Upload}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5424)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.muchmore.www.chasquido.Upload.onCreate(Upload.java:30)
at android.app.Activity.performCreate(Activity.java:6093)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2434)
            at android.app.ActivityThread.access$800(ActivityThread.java:162)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5424)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Home.java
package com.muchmore.www.chasquido;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.ImageView;
import android.content.pm.PackageInfo;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.widget.ImageButton;
import android.view.View;
// new imports
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class Home extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
Button btnShowLocation;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Media Player
Runnable backgroundSound = new Runnable() {
#Override
public void run() {
MediaPlayer mediaPlayer1= MediaPlayer.create(Home.this, R.raw.welcome_message);
mediaPlayer1.start();
MediaPlayer mediaPlayer2= MediaPlayer.create(Home.this, R.raw.welcome_tone);
mediaPlayer2.start();
}
};
Thread media = new Thread(backgroundSound);
media.start();
// Media Player
// Font
final TextView userMessage = (TextView) findViewById(R.id.welcome_tag);
Typeface customWelcomeMessage = (Typeface)Typeface.createFromAsset(getAssets(), "PoiretOne-Regular.ttf");
userMessage.setTypeface(customWelcomeMessage);
// Font
// Intent Import and show top Text
Bundle achieve = getIntent().getExtras();
Boolean anonymousUser = false;
if(achieve == null){
anonymousUser = true;
return;
}
String userName= achieve.getString("Username");
if(anonymousUser == false) {
userMessage.setText("Welcome " + userName + ", You can now take a snap, edit it and upload it to the Server.");
}
if(anonymousUser == true){
userMessage.setText("Welcome Annoymous User, You can't do anything here. Buzz off!!");
}
// Intent Import and show top Text
// GPS
Runnable r = new Runnable() {
#Override
public void run() {
btnShowLocation = (Button)findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(Home.this);
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(
getApplicationContext(),
"Your Location is -\nLat: " + latitude + "\nLong: "
+ longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
}
};
Thread th = new Thread(r);
th.start();
// GPS
// CAMERA BUTTON IMPLEMENTATION
ImageButton cameraButton = (ImageButton)findViewById(R.id.imageButton);
imageView = (ImageView)findViewById(R.id.imageView);
/* Disable the button if the user doesn't have camera */
if(!hasCamera())
cameraButton.setEnabled(false);
// CAMERA BUTTON IMPLEMENTATION
}
// Upload View Load
public void loadUpload(View view){
Log.d("MyMessage", "On Upload Button Click");
Intent intent = new Intent(Home.this, Upload.class);
startActivity(intent);
Log.d("MyMessage", "Starting Intent");
}
//
// Check if the user has a camera
private boolean hasCamera(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
// Launching the camera
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture and pass results along to onActivityResult
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
// If you want to return the image taken
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
//Get the photo
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
imageView.setImageBitmap(photo);
}
}
activity_home.xml
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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.muchmore.www.chasquido.Home"
android:background="#drawable/home_background"
android:id="#+id/home_activity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome User!!!"
android:id="#+id/welcome_tag"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#000"
/>
<ImageButton
android:layout_width="90dp"
android:layout_height="90dp"
android:id="#+id/imageButton"
android:background="#drawable/camera_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="launchCamera"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:minHeight="300dp"
android:minWidth="300dp"
android:layout_above="#+id/imageButton"
android:layout_centerHorizontal="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location"
android:id="#+id/show_location"
android:layout_above="#+id/imageView"
android:layout_toRightOf="#+id/imageButton"
android:layout_toEndOf="#+id/imageButton" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Photo"
android:id="#+id/upload"
android:layout_above="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:onClick="loadUpload" />
</RelativeLayout>
Upload.java
package com.muchmore.www.chasquido;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Upload extends Activity {
private static final int MY_INTENT_CLICK=302;
private TextView txta;
private Button btn_selectImage;
String myGlobalImagePath = "";
Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txta = (TextView) findViewById(R.id.textView1);
btn_selectImage = (Button) findViewById(R.id.btn_selectImage);
btn_selectImage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),MY_INTENT_CLICK);
}
});
r = new Runnable() {
#Override
public void run() {
Ftp obj = new Ftp();
obj.ftpConnect("cp.mdurtk.in", "cp.mdurtk.in|cp", "cp#123", 21);
//obj.ftpUpload(myGlobalImagePath,"file.jpg", "/vikas");
obj.ftpMyUpload(myGlobalImagePath);
}
};
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == MY_INTENT_CLICK)
{
if (null == data) return;
String selectedImagePath;
Uri selectedImageUri = data.getData();
//MEDIA GALLERY
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
myGlobalImagePath = selectedImagePath;
Log.i("Image File Path", ""+selectedImagePath);
txta.setText("File Path : \n"+selectedImagePath); }
}
Thread t = new Thread(r);
t.start();
}
}
activity_upload.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Howdy Buddy! Select an image from your device and the image will be automatically uploaded to the server. You need not to do anything. Isn't that cool? Well yaa cool app for cool buddies."
android:textSize="14sp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_selectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="Select Image" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
You are setting wrong layout.xml as the content View of Upload Activity.
You should do
setContentView(R.layout.activity_upload);
instead of doing
setContentView(R.layout.activity_main);
You are attempting to call a method on a null object on your Upload.java, line 30.

Categories

Resources