I am making simple Android app to load photo from external resources, internal resources or openGL draw.
I tried to load photo with Picasso library for Android, but experiencing:
java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
at com.gornik.choosephoto.MainActivity$1.onClick(MainActivity.java:62)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10813)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Below is my code for MainActivity.java and activity_photo_from_external_resources.xml:
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button submitBtn;
private ImageView externalPhotoView;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onClickListener();
}
public void onClickListener(){
radioGroup = (RadioGroup)findViewById(R.id.allOptions);
submitBtn = (Button)findViewById(R.id.button);
submitBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if(radioGroup.getCheckedRadioButtonId() == -1){
Toast.makeText(MainActivity.this, "Select an option, please", Toast.LENGTH_SHORT).show();
}
else {
int selectedOption = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(selectedOption);
Toast.makeText(MainActivity.this,
radioButton.getText().toString(),
Toast.LENGTH_SHORT).show();
String verifyOption = radioButton.getText().toString();
switch (verifyOption) {
case "Photo from external resources":
Intent intent = new Intent(MainActivity.this, PhotoFromExternalResourcesActivity.class);
startActivity(intent);
externalPhotoView = (ImageView)findViewById(R.id.externalImage);
Picasso.with(getApplicationContext()).load(R.drawable.example_image).into(externalPhotoView);
break;
case "Photo from Your resources":
verifyStoragePermissions(MainActivity.this);
Intent intent2 = new Intent(MainActivity.this, PhotoFromYourResourceActivity.class);
startActivity(intent2);
break;
case "OpenGL draw":
Intent intent3 = new Intent(MainActivity.this, OpenGLDrawActivity.class);
startActivity(intent3);
break;
}
}
}
}
);
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
<?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="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.gornik.choosephoto.PhotoFromExternalResourcesActivity">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/externalImage"
android:src="#drawable/example_image"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
What is the reason for target not null and how can i correct the code?
You can only access Views that are inflated in the current activity.
You are trying to access externalImage inside MainActivity, but externalImage does not exist in activity_main.xml, so the externalPhotoView reference will always be null.
Since the externalImage View is located in activity_photo_from_external_resources.xml, which presumably is inflated inside your PhotoFromExternalResourcesActivity class, you should move the Picasso related code to your PhotoFromExternalResourcesActivity class.
The reference of the ImageView must be null:
externalPhotoView = (ImageView)findViewById(R.id.externalImage);
Thats why you have the exception:
IllegalArgumentException Target must not be null
When try to load the target (.into(externalPhotoView)) :
Picasso.with(getApplicationContext()).load(R.drawable.example_image).into(externalPhotoView);
Ensure that your ImageView with id #+id/externalImage really exists in your activity_main.xml layout.
MainActivity is inflating activity_main.xml and not activity_photo_from_external_resources.xml.
Related
Very strange problem here. I'm going around in circles with it!
Day/Night mode seems to be working fine throughout my app...but for INVISIBLE drawables only, it is not working on initial load.
I have 2 xml drawable folders:
drawable and drawable-night with matching .png filenames
I have two values folders:
values with colors.xml, styles.xml, ic_launcher_background.xml and strings.xml - and also -
values-night with colors.xml and styles.xml
In the app I set the Mode using a toggle switch for Day/Night mode as per below. This seems to work fine.
dayNightMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
System.out.println("Not Checked");
InitApplication.getInstance().setIsNightModeEnabled(true, context);
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
dayNightMode.setText("Night Mode");
} else {
System.out.println("Checked");
InitApplication.getInstance().setIsNightModeEnabled(false, context);
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
dayNightMode.setText("Day Mode");
}
}
});
The InitApplication class being called by the above code is:
package com.dmurphy.remotescrumpoker;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class InitApplication extends Application {
public static final String NIGHT_MODE = "NIGHT_MODE";
private boolean isNightModeEnabled = false;
private static InitApplication singleton = null;
public static InitApplication getInstance() {
if(singleton == null)
{
singleton = new InitApplication();
}
return singleton;
}
#Override
public void onCreate() {
super.onCreate();
singleton = this;
Context appContext = this.getApplicationContext();
SharedPreferences sharedPreferences = appContext.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
isNightModeEnabled = sharedPreferences.getBoolean(NIGHT_MODE, true);
Log.i("onCreate1_", String.valueOf(isNightModeEnabled));
}
public boolean isNightModeEnabled(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
isNightModeEnabled = sharedPreferences.getBoolean(NIGHT_MODE, true);
Log.i("onCreate11_", String.valueOf(isNightModeEnabled));
return isNightModeEnabled;
}
public void setIsNightModeEnabled(boolean isNightModeEnabled, Context context) {
this.isNightModeEnabled = isNightModeEnabled;
Log.i("onCreate111_", String.valueOf(isNightModeEnabled));
SharedPreferences sharedPreferences = context.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
sharedPreferences.edit().putBoolean(NIGHT_MODE, isNightModeEnabled).apply();
Log.i("onCreate1111_", String.valueOf(isNightModeEnabled));
}
}
I also have an Activity_Poker activity. Everything works fine, if I change the switch the app changes.
I also have a startup activity Activity_Splash and in the onCreate I check the mode:
if (InitApplication.getInstance().isNightModeEnabled(context)) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Log.i(TAG, "onCreate1_" + "Mode Night Yes");
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.i(TAG, "onCreate1_" + "Mode Night No");
}
setContentView(R.layout.activity__splash);
The startup works fine. When I close the app and restart, the background color etc. is correct for both Modes. I have 3 drawables VISIBLE on the activity at all times. These also change fine between the two alternative modes.
However, I have 9 drawables which are INVISIBLE by default. These become VISIBLE onCreate, but they are always showing DAY_MODE on every load.
NOTE: The drawables are not in the wrong folders. The correct colors are in the correct folders. The color of the 9 .png files which are not working, matches the 3 VISIBLE drawables which work fine. Just the default INVISIBLE ones are not populating from the drawables-night folder onCreate.
If I restart the Activity using the inApp user menu, the activity is recreated correctly with the NIGHT_MODE or DAY_MODE drawables as applicable. But the NIGHT_MODE drawables (Fors ones which are INVISIBLE by default) are never used on startup.
EXPECTED OUTCOME: On Startup, ImageView's which are INVISIBLE are changed to VISIBLE and populated with drawables for DAY_MODE ordrawables-night for NIGHT_MODE.
ACTUAL OUTCOME: On Startup, ImageView's which are INVISIBLE are changed to VISIBLE and populated with drawables for DAY_MODE ordrawables for NIGHT_MODE.
Activity_Poker.java
public class Activity_Poker extends AppCompatActivity {
[snip]
Activity passedActivity = Activity_Poker.this;
[snip]
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poker);
drawerLayout = findViewById(R.id.drawer_layout);
[snip]
final String methodName = "onCreate";
mAuth = FirebaseAuth.getInstance();
String userId = mAuth.getUid();
[snip]
//Setup the UI for the selected game type
int cardType = sharedPreferences.getInt("cardType", 0);
Log.i(TAG, "Selected SharedPref Record: " + cardType);
callSetupUI.setupLocalActive(passedActivity, cardType);
[snip]
}
NOTE: cardType above shows correctly == 5 from the Logcat.
SetupUI.java
public void setupLocalActive(Activity passedActivity, int cardType) {
ImageView card4 = passedActivity.findViewById(R.id.pokerCard4);
ImageView card4img = passedActivity.findViewById(R.id.pokerCard4img);
ImageView card5 = passedActivity.findViewById(R.id.pokerCard5);
ImageView card5img = passedActivity.findViewById(R.id.pokerCard5img);
ImageView card6 = passedActivity.findViewById(R.id.pokerCard6);
ImageView card6img = passedActivity.findViewById(R.id.pokerCard6img);
ImageView card7 = passedActivity.findViewById(R.id.pokerCard7);
ImageView card7img = passedActivity.findViewById(R.id.pokerCard7img);
ImageView card8 = passedActivity.findViewById(R.id.pokerCard8);
ImageView card8img = passedActivity.findViewById(R.id.pokerCard8img);
ImageView card9 = passedActivity.findViewById(R.id.pokerCard9);
ImageView card9img = passedActivity.findViewById(R.id.pokerCard9img);
ImageView card11 = passedActivity.findViewById(R.id.pokerCard11);
ImageView card11img = passedActivity.findViewById(R.id.pokerCard11img);
TextView card4TextView = passedActivity.findViewById(R.id.textViewPokerCard4);
TextView card5TextView = passedActivity.findViewById(R.id.textViewPokerCard5);
TextView card6TextView = passedActivity.findViewById(R.id.textViewPokerCard6);
TextView card7TextView = passedActivity.findViewById(R.id.textViewPokerCard7);
TextView card8TextView = passedActivity.findViewById(R.id.textViewPokerCard8);
TextView card9TextView = passedActivity.findViewById(R.id.textViewPokerCard9);
TextView card10TextView = passedActivity.findViewById(R.id.textViewPokerCard10);
TextView card11TextView = passedActivity.findViewById(R.id.textViewPokerCard11);
TextView card12TextView = passedActivity.findViewById(R.id.textViewPokerCard12);
TextView card13TextView = passedActivity.findViewById(R.id.textViewPokerCard13);
TextView card14TextView = passedActivity.findViewById(R.id.textViewPokerCard14);
TextView card15TextView = passedActivity.findViewById(R.id.textViewPokerCard15);
Log.i(TAG, "Selected SharedPref Record UI CardType into Switch: " + cardType);
switch (cardType){
case 1:
[snip]
case 2:
[snip]
case 3:
[snip]
case 4:
[snip]
case 5:
Log.i(TAG, "Selected SharedPref Record Setting UI: " + cardType);
card10.setVisibility(card10.INVISIBLE);
card12.setVisibility(card12.INVISIBLE);
card13.setVisibility(card13.INVISIBLE);
card14.setVisibility(card14.INVISIBLE);
card15.setVisibility(card15.INVISIBLE);
card4TextView.setVisibility(card4TextView.INVISIBLE);
card5TextView.setVisibility(card5TextView.INVISIBLE);
card6TextView.setVisibility(card6TextView.INVISIBLE);
card7TextView.setVisibility(card7TextView.INVISIBLE);
card8TextView.setVisibility(card8TextView.INVISIBLE);
card9TextView.setVisibility(card9TextView.INVISIBLE);
card10TextView.setVisibility(card10TextView.INVISIBLE);
card11TextView.setVisibility(card10TextView.INVISIBLE);
card12TextView.setVisibility(card12TextView.INVISIBLE);
card13TextView.setVisibility(card13TextView.INVISIBLE);
card14TextView.setVisibility(card14TextView.INVISIBLE);
card15TextView.setVisibility(card15TextView.INVISIBLE);
card4img.setImageResource(R.drawable.chihuahua);
card5img.setImageResource(R.drawable.dachshund);
card6img.setImageResource(R.drawable.beagle);
card7img.setImageResource(R.drawable.spaniel);
card8img.setImageResource(R.drawable.boxer);
card9img.setImageResource(R.drawable.shepard);
card11img.setImageResource(R.drawable.dane);
card4img.setVisibility(card4img.VISIBLE);
card5img.setVisibility(card5img.VISIBLE);
card6img.setVisibility(card6img.VISIBLE);
card7img.setVisibility(card7img.VISIBLE);
card8img.setVisibility(card8img.VISIBLE);
card9img.setVisibility(card9img.VISIBLE);
card11img.setVisibility(card11img.VISIBLE);
break;
default:
[snip]
break;
}
}
activity_poker.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="260dp">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="32dp">
[snip]
<ImageView
android:id="#+id/pokerCard5"
android:layout_width="88dp"
android:layout_height="104dp"
android:layout_marginTop="16dp"
android:background="#color/colorPrimary"
android:contentDescription="#string/localCardSelectcontent"
android:onClick="card8clicked"
app:layout_constraintEnd_toStartOf="#+id/pokerCard6"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/pokerCard4"
app:layout_constraintTop_toBottomOf="#+id/pokerCard2" />
<ImageView
android:id="#+id/pokerCard5img"
android:layout_width="72dp"
android:layout_height="88dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:contentDescription="#string/localCardSelectcontent"
android:onClick="localcard5clicked"
android:visibility="invisible"
app:layout_constraintStart_toStartOf="#+id/pokerCard5"
app:layout_constraintTop_toTopOf="#+id/pokerCard5"
app:srcCompat="#drawable/dachshund" />
<TextView
android:id="#+id/textViewPokerCard5"
android:layout_width="88dp"
android:layout_height="104dp"
android:onClick="localcard5clicked"
android:gravity="center"
android:includeFontPadding="false"
android:textColor="#color/colorPrimaryDark"
android:textSize="44sp"
android:textStyle="normal|bold"
app:layout_constraintStart_toStartOf="#+id/pokerCard5"
app:layout_constraintTop_toTopOf="#+id/pokerCard5" />
<ImageView
android:id="#+id/pokerCard4"
android:layout_width="88dp"
android:layout_height="104dp"
android:background="#color/colorPrimary"
android:contentDescription="#string/localCardSelectcontent"
android:onClick="card5clicked"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="#+id/pokerCard5"
app:layout_constraintEnd_toStartOf="#+id/pokerCard5"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/pokerCard4img"
android:layout_width="72dp"
android:layout_height="88dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:contentDescription="#string/localCardSelectcontent"
android:onClick="localcard4clicked"
android:visibility="invisible"
app:layout_constraintStart_toStartOf="#+id/pokerCard4"
app:layout_constraintTop_toTopOf="#+id/pokerCard4"
app:srcCompat="#drawable/chihuahua" />
<TextView
android:id="#+id/textViewPokerCard4"
android:layout_width="88dp"
android:layout_height="104dp"
android:onClick="localcard4clicked"
android:gravity="center"
android:includeFontPadding="false"
android:textColor="#color/colorPrimaryDark"
android:textSize="44sp"
android:textStyle="normal|bold"
app:layout_constraintStart_toStartOf="#+id/pokerCard4"
app:layout_constraintTop_toTopOf="#+id/pokerCard4" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:onClick="onSwitchChange"
app:headerLayout= "#layout/nav_header_main"
app:menu="#xml/drawer_view" >
</com.google.android.material.navigation.NavigationView>
This is probably not the correct solution, but I implemented a workaround.
In Activity_Splash I added a bool to indicate that its the initial startup.
SharedPreferences sharedPreferences = Activity_Splash.this.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
sharedPreferences.edit().putBoolean("initialStartup", true).apply();
In Activity_Poker I retrieved the bool and if NIGHT_MODE is enabled and 'initialStartup' is true, I restart the Activity_Poker to reset the UI.
boolean initialStartup = sharedPreferences.getBoolean("initialStartup", false);
if (InitApplication.getInstance().isNightModeEnabled(context) && initialStartup) {
callUserMenu.menuAction(TAG, methodName, context, 5, passedActivity); //This triggers my Intent to restart the activity
sharedPreferences.edit().remove("initialStartup").apply();
}
Still have no idea whats actually causing this.
My Activity currently holds everything! I would love to have my ListView in another Activity. I have tried cutting and putting in a new Activity, but it can't seem to work because of an error that has to do with the .setText("") on the last line.
Button save;
ArrayList<String> addArray = new ArrayList<String>();
EditText edit;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailsctivity);
Intent intent = getIntent();
save = (Button) findViewById(R.id.confirm);
edit = (EditText) findViewById(R.id.input);
listView = (ListView) findViewById(R.id.list);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getInput = edit.getText().toString();
if (addArray.contains(getInput)){
Toast.makeText(getBaseContext(), "Item Added!", Toast.LENGTH_SHORT).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(getBaseContext(), "NO ITEM!", Toast.LENGTH_SHORT).show();
}
else {
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DetailsActivity.this,
android.R.layout.simple_list_item_1,
addArray);
listView.setAdapter(adapter);
((EditText) findViewById(R.id.input)).setText("");
}
}
});
}
The Intent intent = getIntent(); comes from a button from my MainActivity.
I guess one step of it is to move the array adapter into the new Activity, which I did as well... but failed again. I do understand the usage of intents as well! Maybe something is missing somewhere?
My layout goes like this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_detailsctivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.shoppinglist.pixelite.shoppinglist.DetailsActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/input"
android:hint="#string/newProduct"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/list"
android:layout_below="#id/input"
>
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/confirm"
android:hint="#string/add"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
I have two Activity, A and B. In A, it has a listView and a button. In B, it has imageView and editText . Now what I trying to achieve is return the text from B to listView A.
Activity A
View claims = inflater.inflate(R.layout.receipt_text, container, false);
listV = (ListView) claims.findViewById(R.id.listView);
String [] status ={"Type of Claims :" +name,"Amount :" +result};
adapter=new ArrayAdapter<String>(this,R.layout.claims,status);
listV.setAdapter(adapter);
return claims;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive text from B
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
break;
}
Activity B
ImageView viewImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt = (EditText) findViewById(R.id.editText36);
txt1=(TextView)findViewById(R.id.textView57);
Button b = (Button) findViewById(R.id.button17);
addListenerOnButton();
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Global.img=null;
Intent i = new Intent(Project1.this, C.class);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ // receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img);
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
}
receipt_text.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/text" android:textSize="20sp" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
claims.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
</android.support.v4.widget.DrawerLayout>
Error
11-16 10:57:24.696 30313-30313/com.example.project.project
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 30313
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
The constructor for ArrayAdapter is wrong.
adapter=new ArrayAdapter<String>(this,R.layout.claims,c);
Instead of passing an int into the ArrayAdapter constructor, creating a List and pass it in. Later add the data you get from Activity B to the list.
List<String> list = new ArrayList<>();
adapter=new ArrayAdapter<String>(this, R.layout.claims, list);
When you get the data back from ActivityB, do this
String data = Integer.toString(c);
list.add(data);
adapter.notifyDataSetChanged();
CarSelection.java:
public class CarSelection extends Activity {
private Spinner spinner1;
// array list for spinner adapter
private ArrayList<Category> brandsList;
ProgressDialog pDialog;
// Url to get all categories
private String URL_CATEGORIES = "http://10.0.2.2/view/get_brands.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_selection);
Bundle b = getIntent().getExtras();
if(b != null){
String selection1=b.getString("pickup");
String selection2=b.getString("pickdate");
String selection3=b.getString("picktime");
String selection4=b.getString("dropoff");
String selection5=b.getString("dropdate");
String selection6=b.getString("droptime");
TextView text1=(TextView)findViewById(R.id.pickup);
TextView text2=(TextView)findViewById(R.id.pickdate);
TextView text3=(TextView)findViewById(R.id.picktime);
TextView text4=(TextView)findViewById(R.id.dropoff);
TextView text5=(TextView)findViewById(R.id.dropdate);
TextView text6=(TextView)findViewById(R.id.droptime);
text1.setText(selection1);
text2.setText(selection2);
text3.setText(selection3);
text4.setText(selection4);
text5.setText(selection5);
text6.setText(selection6);
}
else{
Toast.makeText(CarSelection.this,"Haven't Received any data yet", Toast.LENGTH_LONG).show();
}
brandsList = new ArrayList<Category>();
// Show the Up button in the action bar.
setupActionBar();
addListenerOnSpinnerItemSelection();
new GetCategories().execute();
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinnerbrand);
spinner1.setOnItemSelectedListener(new CarBrandSelection(this));
}
...
}
CarBrandSelection.java:
public class CarBrandSelection implements OnItemSelectedListener {
private TextView pdestination, pdate, ptime, ddestination, ddate, dtime;
Activity mActivity;
public CarBrandSelection(Activity activity) {
mActivity = activity;
}
public void onClick(View v) {
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos){
case 1:
pdestination=(TextView) findViewById(R.id.pickup);
pdate=(TextView) findViewById(R.id.pickdate);
ptime=(TextView) findViewById(R.id.picktime);
ddestination=(TextView) findViewById(R.id.dropoff);
ddate=(TextView) findViewById(R.id.dropdate);
dtime=(TextView) findViewById(R.id.droptime);
Bundle b=new Bundle();
b.putString("destination", pdestination.getText().toString());
Intent intent = new Intent(mActivity, FirstListView.class);
intent.putExtras(b);
mActivity.startActivity(intent);
break;
case 2:
Intent intent1 = new Intent(mActivity, SecondListView.class);
mActivity.startActivity(intent1);
break;
case 3:
Intent intent2 = new Intent(mActivity, ThirdListView.class);
mActivity.startActivity(intent2);
break;
case 4:
Intent intent3 = new Intent(mActivity, FourthListView.class);
mActivity.startActivity(intent3);
break;
// and so on
// .....
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
FirstListView.java:
public class FirstListView extends Activity implements FetchDataListener{
private ProgressDialog dialog;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Bundle b = getIntent().getExtras();
String selection1=b.getString("destination");
TextView text1=(TextView)findViewById(R.id.p_destination);
text1.setText(selection1);
initView();
addListenerOnListItemSelection();
}
main_activity.xml
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="235dp"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"/>
<LinearLayout
android:id="#+id/linealayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/p_destination"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/drop_off" />
</LinearLayout>
activity_car_selection.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".CarSelection" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/vehicle_brand"/>
<TextView android:id="#+id/pickup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<TextView android:id="#+id/pickdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<TextView android:id="#+id/picktime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<TextView android:id="#+id/dropoff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<TextView android:id="#+id/dropdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<TextView android:id="#+id/droptime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
I really need help to solve this problem. I want to do like when a user clicks on a specific item in the spinner (R.id.spinnerbrand), the data from the textview (R.id.pickup) will be passed to the next activity which is FirstListView.java. I'm not sure whether I do it correctly because the data cannot be passed. Really appreciate if someone can help to solve this. Thanks a lot
If you want to get the data from the spinner you can use:
String selected = parent.getItemAtPosition(pos).toString();
And for passing the data to the other activity basically this is what you need to do:
in the first activity you should create a Intent set the Action and add what you need:
Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);
and in the second activity:
Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);
one of the get-functions will give return you the value, depending on the datatype you are passing through.
or in the second activity, for example i want to get the value of name that I include at:
intent.putExtra("name", name); on first class, for that you can simply make:
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
The application now is crashing due to nullpointerexception. I have found many different similar problems on google, however, none of the solutions worked. This app is supposed to forward a call, where the number to receive the forwarded calls are stored within the shared preferences. As for the numbers to forward are stored within a database. If possible, do guide me on how to get data from the database as well. Thanks
These are the logcats:
02-12 15:09:07.745: E/AndroidRuntime(4827): Caused by: java.lang.NullPointerException
02-12 15:09:07.745: E/AndroidRuntime(4827): at com.example.awkwardpanda_redirectcall.MainActivity.onCreate(MainActivity.java:33)
02-12 15:09:07.745: E/AndroidRuntime(4827): at android.app.Activity.performCreate(Activity.java:5158)
02-12 15:09:07.745: E/AndroidRuntime(4827): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-12 15:09:07.745: E/AndroidRuntime(4827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
02-12 15:09:07.745: E/AndroidRuntime(4827): ... 11 more
This is my mainactivity.java
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch switch1 = (Switch) findViewById(R.id.switch1);
EditText editText1 = (EditText) findViewById(R.id.editText1);
SharedPreferences preferences;
preferences = PreferenceManager.getDefaultSharedPreferences(this);
final String streditText1 = preferences.getString("Number", "");
editText1.setText(streditText1);
// set the switch to OFF
switch1.setChecked(false);
// attach a listener to check for changes in state
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(getApplicationContext(), "Call Forwarding is activated",Toast.LENGTH_SHORT).show();
callforward("*63*" + streditText1 + "#"); // 0123456789 is the number you want to forward the calls.;
}
else{
Toast.makeText(getApplicationContext(), "Call Forwarding is deactivated",Toast.LENGTH_SHORT).show();
callforward("#81#");
}
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void manage_numbers_onClick(View view) {
Intent myIntent = new Intent(this, Manage_numbers.class);
startActivity(myIntent);
}
private void callforward(String ArrayString)
{
//DBAdapter db = new DBAdapter(this);
//db.getAllContacts().toString();
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager)
this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Intent intentCallForward = new Intent(Intent.ACTION_CALL);
Uri mmiCode = Uri.fromParts("tel", ArrayString, "#");
intentCallForward.setData(mmiCode);
startActivity(intentCallForward);
}
private class PhoneCallListener extends PhoneStateListener
{
private boolean isPhoneCalling = false;
#Override
public void onCallStateChanged(int state, String incomingNumber)
{
if (TelephonyManager.CALL_STATE_RINGING == state)
{
// phone ringing
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state)
{
// active
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state)
{
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
if (isPhoneCalling)
{
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
This is my xml file
<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="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="#string/checktoconfirm"/>
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:inputType="phone"
android:text="#string/receivenumbertext" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginTop="10dp"
android:text="#string/savebtn" />
</LinearLayout>
I see no #+id/switch1 in your layout; findViewById() will return null.
UPD: You probably would like to read Re-using Layouts with <include/>
Probably the value of "editText1" is Null which is causing the crash. Check and fix it to incluidng it properly in xml & referncing in the code to remove the crash