Attempt to invoke virtual method .(context menu)... on a null object reference - java

Hello people Im always getting this error in debugger and the app will not start. If I am deleting the contextmenu it is working...
public class MainActivity extends AppCompatActivity {
public int[] buttonArray = {R.id.button1, R.id.button2, R.id.button3}; // Button Array
public int[] soundsArray = {R.raw.sound1, R.raw.sound2, R.raw.sound3}; // Sound Array
private int[] tabIcons = {
R.drawable.infoicon,
R.drawable.soundicon,
R.drawable.startop
};
int counters=1;
int counter=1;
final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;
public String ordnerpfad = Environment.getExternalStorageDirectory() + "/Sounds";
public String soundpfad = ordnerpfad + "/sound.mp3";
public File ordnerfile = new File(ordnerpfad);
public File soundfile = new File(soundpfad);
public Uri urisound = Uri.parse(soundpfad);
public byte[] byte1 = new byte [1024];
public int zwischenspeicher = 0;
public InputStream is1;
public FileOutputStream fos;
public Intent teilintent;
InterstitialAd mInterstitialAd;
TabLayout tabLayout;
ViewPager viewPager;
MediaPlayer MainMMP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
public void run() {
requestNewInterstitial();
}
}, 14000);
MobileAds.initialize(getApplicationContext(), "xxxxxxxxxxxxxxx");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("2BB7955A07F972AC2D1DA7617768CE01")
.build();
mAdView.loadAd(request);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("xxxxxxxxxxxxxx");
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
for (int i = 0; i < buttonArray.length; i++) {
Button contextMenuButton = (Button) findViewById(buttonArray[i]);
registerForContextMenu(contextMenuButton);
}
MainMMP = MediaPlayer.create(this, R.raw.sound1);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Close this App?\n\nWe are happy for each Feedback :) ")
.setCancelable(false)
.setNeutralButton("Rate Us", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int rate){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http...xxxx..xxx"));
startActivity(intent);
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainMMP.release();
finish();
System.exit(0);
}
})
.setNegativeButton("No", null)
.show();
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("2BB7955A07F972AC2D1DA7617768CE01")
.build();
mInterstitialAd.loadAd(adRequest);
}
public void Share(View view){
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey, check this Soundboard");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, view.getId(), 0, "Action 1");
menu.add(0, view.getId(), 0, "Action 2");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals("Action 1")){function1(item.getItemId());}
else if(item.getTitle().equals("Action 2")){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
for (int i=0; i<buttonArray.length; i++) {
if (id == buttonArray[i]) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
if (!ordnerfile.exists()) {
try {
ordnerfile.mkdir();
Toast.makeText(getApplicationContext(), "Created Folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
}
try {
is1 = getResources().openRawResource(soundsArray[i]);
fos = new FileOutputStream(soundfile);
while ((zwischenspeicher = is1.read(byte1)) > 0) {
fos.write(byte1, 0, zwischenspeicher);
}
is1.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
teilintent = new Intent(Intent.ACTION_SEND);
teilintent.setType("audio/*");
teilintent.putExtra(Intent.EXTRA_STREAM, urisound);
startActivity(Intent.createChooser(teilintent, "Share this Sound..."));
}
else {
ActivityCompat.requestPermissions(MainActivity.this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
}
return;
}
}
}
public void function2(int id){
Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();}
public void MainMMP(View view) {
for (int i=0; i<buttonArray.length; i++) {
if (view.getId() == buttonArray[i]) {
MainMMP.release();
MainMMP = MediaPlayer.create(MainActivity.this, soundsArray[i]);
MainMMP.start();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ordnerfile.mkdir();
Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
}
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[2]);
tabLayout.getTabAt(2).setIcon(tabIcons[1]);
tabLayout.getTabAt(3).setIcon(tabIcons[1]);
tabLayout.getTabAt(4).setIcon(tabIcons[1]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentFavourite(), "");
adapter.addFrag(new Fragment1(), "Top Sounds");
adapter.addFrag(new Fragment2(), "Sounds 1");
adapter.addFrag(new Fragment3(), "Sounds 2");
adapter.addFrag(new Fragment4(), "Sounds 3");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter(FragmentManager manager) {
super(manager);}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
private void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Now my tab1.xml
Actual there are more buttons but just for some tests I do it with the first 3
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal|center"
android:layout_margin="15dp"
android:minHeight="90dp">
<Button
android:id="#+id/button1"
android:onClick="MainMMP"
android:text="Fun Fun\nFun"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/button2"
android:onClick="MainMMP"
android:text="Sing, Dance,\nPretend"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button3"
android:onClick="MainMMP"
android:text="Kazoo\nSound1"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp" />
<Button
android:id="#+id/button4"
android:onClick="MainMMP"
android:text="Kaaaa-\nzooo"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button5"
android:onClick="MainMMP"
android:text="Kazoo\nSound2"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button6"
android:onClick="MainMMP"
android:text="Just Kazoo\nit"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button7"
android:onClick="MainMMP"
android:text="Special-\nfriends"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button8"
android:onClick="MainMMP"
android:text="I just \n wanna say"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button9"
android:onClick="MainMMP"
android:text="Before I\n met you"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button10"
android:onClick="MainMMP"
android:text="Right\n by my side"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button11"
android:onClick="MainMMP"
android:text="Sing a Song\n for you"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button12"
android:onClick="MainMMP"
android:text="Your my\n Friend"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button13"
android:onClick="MainMMP"
android:text="I was \n alone"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button14"
style="?android:attr/borderlessButtonStyle"
android:onClick="MainMMP"
android:text="Looking\n for a friend"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button15"
android:onClick="MainMMP"
style="?android:attr/borderlessButtonStyle"
android:text="Speeeecial-\nfrieeeend"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
</TableRow>
</TableLayout>
</ScrollView>
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.apsps.someappsa..Soundboard, PID: 10970 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apsps.someappsa.Soundboard/com.apsps.someappsa.Soundboard.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnCreateContextMenuListener(android.view.View$OnCreateContextMenuListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnCreateContextMenuListener(android.view.View$OnCreateContextMenuListener)' on a null object reference at android.app.Activity.registerForContextMenu(Activity.java:3227) at com.apsps.someappsa.Soundboard.MainActivity.onCreate(MainActivity.java:86) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Your code for pointing to the button by calling findViewById is throwing a null point exception.
Button contextMenuButton = (Button) findViewById(buttanArray[i]);
registerForContextMenu(contextMenuButton);
Make sure that your buttonArray[i] has got the correct ID of the button and there exist a button in your xml file with that ID.

Related

how to save selected radio button and spinner data by value using rest API?

I am using rest API and facing some issue when embedding an API. How do I save spinner and radio button data by value and using retrofit2.This API is for calculating BMR and BMR Please help!
Here is BMIquestions.java
public class BMIquestions extends AppCompatActivity implements View.OnClickListener{
Button nextbtn;
ImageButton date;
DatePickerDialog datePickerDialog;
EditText age, height, weight;
// Let's assume 1 = male and 0 = female
// Declare a RadioGroup object reference
RadioGroup rgGender;
// Declare RadioButton object references for Male and Female
RadioButton rbMale, rbFemale;
private String gender=null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentHeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if(rbMale.isSelected()){
rbMale.setTag("1");
rbMale.getTag().toString();
if(rbFemale.isSelected()){
rbFemale.setTag("0");
rbFemale.getTag().toString();
}
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
String[] level = new String[]{"Not Very Activ", "Lightly Active", "Active", "Very Active"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
R.layout.drop_down_items,
level
);
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.type);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(BMIquestions.this, autoCompleteTextView.getText().toString(), Toast.LENGTH_SHORT).show();
if(autoCompleteTextView.getText().toString().equals("Lightly Active")){
autoCompleteTextView.setTag("1.55");
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
// Calender class 's instance and get current,date ,month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);//current year
int mMonth = c.get(Calendar.MONTH);//current month
int mDay = c.get(Calendar.DAY_OF_MONTH);//current date
final int noofyears = (int) (mYear - c.get(Calendar.YEAR)); //calculate age
//date picker dialog
datePickerDialog = new DatePickerDialog(BMIquestions.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
age.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
DatePicker dp = datePickerDialog.getDatePicker();
WindowManager.LayoutParams params = datePickerDialog.getWindow().getAttributes();
//params.gravity = Gravity.CENTER_HORIZONTAL;
params.width = 50; // dialogWidth;
params.height = 100; // dialogHeight;
datePickerDialog.show();
}
});
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
case R.id.male:
gender="0";
break;
case R.id.female:
rbFemale.setTag("0");
gender=rbFemale.getTag().toString();
break;
}
}
public void openHomePage() {
String userHeight = height.getText().toString();
String userWeight = weight.getText().toString();
String userAge = age.getText().toString();
HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("height", userHeight);
meMap.put("age", userAge);
meMap.put("gender", gender);
//meMap.put("activity_level",act);
meMap.put("current_weight",userWeight);
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(meMap);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BMIquestions.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(BMIquestions.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Intent i=new Intent(BMIquestions.this,HomePage.class);
startActivity(i);
}
}
Here is activity_bmiquestions.xml
<?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=".ui.questions.BMIquestions">
<TextView
android:id="#+id/targetWeight"
android:layout_width="386dp"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_regular"
android:gravity="center"
android:paddingStart="12dp"
android:paddingTop="60dp"
android:text="Tell us About Youself"
android:textColor="#color/black"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="122dp"
android:fontFamily="#font/roboto_regular"
android:text="Gender:"
android:textColor="#color/black"
android:textSize="14dp" />
<RadioGroup
android:id="#+id/gender_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="142dp"
android:paddingStart="24dp"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
/>
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
</RadioGroup>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/age"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="DD/MM/YYYY" />
<ImageButton
android:id="#+id/calender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_baseline_calendar_today_24" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Height in centimeter"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentHeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your height"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="cm"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="When were you born ?"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Weight in kilogram"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentWeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your weight" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:textColor="#color/black" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="440dp"
android:layout_marginStart="10dp">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="80dp"
android:hint="Activity Level" >
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:inputType="none">
</AutoCompleteTextView>
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
<android.widget.Button
android:id="#+id/Next"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="21dp"
android:background="#color/dark_grey"
android:text="Next"
android:textColor="#color/white"
android:textSize="15sp"
android:textStyle="bold"></android.widget.Button>
</RelativeLayout>
Here is Api Interface
public interface Api{
//GetCalculations
#POST("calculation")
Call<QuestionResponse> calculation(
#Body HashMap<String, String> body
);
}
Here is RetrofitClient.java
package com.example.signup.ui.api;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
//singeleton class defining retrofit client
//define base url
//initialize retrofit object
private static final String BASE_URL = "http://xxx.xxx.xxx.xxx:xxxx/api/";
private static RetrofitClient retrofitClient;
private static Retrofit retrofit;
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//return instances when above method call
public static synchronized RetrofitClient getInstance() {
if (retrofitClient==null) {
retrofitClient = new RetrofitClient();
}
return retrofitClient;
}
public Api getApi() {
return retrofit.create(Api.class);
}
}
How can I fix this problem?

java.lang.IllegalArgumentException: uri cannot be null

I am getting and error while uploading an image and storing data to Firebase. I am using Bitmap to display the images. After submitting the data the app crashes and returns to the previous Activity. Also, when I pick an image from the device it is not displaying in the ImageView.
My error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bloodsavelife, PID: 6642
java.lang.IllegalArgumentException: uri cannot be null
at com.google.android.gms.common.internal.Preconditions.checkArgument(com.google.android.gms:play-services-basement##17.2.1:35)
at com.google.firebase.storage.StorageReference.putFile(StorageReference.java:238)
at com.example.bloodsavelife.Activities.MakeRequest.uploadToFirebase(MakeRequest.java:153)
at com.example.bloodsavelife.Activities.MakeRequest.access$000(MakeRequest.java:47)
at com.example.bloodsavelife.Activities.MakeRequest$2.onClick(MakeRequest.java:121)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) I/Process: Sending signal. PID: 6642 SIG: 9
XML file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".Activities.MakeRequest">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="18dp"
android:text="Write your message and add an image for the community, somebody will
defintely help you if possible"
android:textColor="#android:color/black"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/post_image"
android:layout_width="192dp"
android:layout_height="150dp"
android:padding="8dp"
android:src="#drawable/ic_launcher_background_image" />
<Button
android:id="#+id/browse"
android:layout_width="141dp"
android:layout_height="57dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="60dp"
android:background="#drawable/button_bg"
android:gravity="center"
android:text="Browse"
android:textAlignment="gravity"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#drawable/border_background">
<EditText
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:cursorVisible="true"
android:gravity="top"
android:hint="Message to donors and mention for what purpose blood needed Include your
contact and location here."
android:maxLines="15"
android:minLines="7"
android:padding="10dp"
android:textAlignment="gravity"
android:textColor="#android:color/black"
android:textColorHint="#color/DarkGreen"
android:textSize="15sp"
android:textStyle="bold" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/bloodgroup"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Required Blood Group"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="dropdown_menu">
<AutoCompleteTextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/quantity"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Quantity Needed(in ml)"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<Button
android:id="#+id/btn_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="#drawable/button_bg"
android:text="Post Request"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
Java code:
public class MakeRequest extends AppCompatActivity {
EditText message;
TextInputLayout bloodgroup, quantity;
TextView title;
ImageView image;
Uri filepath;
Bitmap bitmap;
Button postReq, browse;
private AutoCompleteTextView dropDownText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_request);
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
browse = findViewById(R.id.browse);
title = findViewById(R.id.title);
image = findViewById(R.id.image);
postReq = findViewById(R.id.btn_post);
dropDownText = findViewById(R.id.dropdown_text);
String[] item = new String[]{
"A+Ve",
"A-Ve",
"B+Ve",
"B-Ve",
"AB+Ve",
"AB-Ve",
"O+Ve",
"O-Ve"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
MakeRequest.this,
R.layout.dropdown_item,
item
);
dropDownText.setAdapter(adapter);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MakeRequest.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "select image"), 1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission,
PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
postReq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadToFirebase();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadToFirebase() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("File Uploader");
dialog.show();
enter code here
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
FirebaseStorage storage = FirebaseStorage.getInstance();
//need improvement by using date and time instead of random method.
StorageReference uploader = storage.getReference("Image1" + new Random().nextInt(100));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
dialog.dismiss();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("RequestPost");
RequestHelper obj = new RequestHelper(message.getText().toString(),
bloodgroup.getEditText().getText().toString(), quantity.getEditText().getText().toString(),
uri.toString());
root.child(bloodgroup.getEditText().getText().toString()).setValue(obj);
message.setText("");
bloodgroup.getEditText().setText("");
quantity.getEditText().setText("");
image.setImageResource(R.drawable.ic_image_black_24dp);
Toast.makeText(getApplicationContext(), "Uploaded",
Toast.LENGTH_LONG).show();
}
});
}
})
.addOnProgressListener(snapshot -> {
float percent = (100 * snapshot.getBytesTransferred()) /
snapshot.getTotalByteCount();
dialog.setMessage("Uploaded:" + (int) percent + "%");
});
}
Try with this code
Pick an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(intent, 1001);
onActivityforresult get Uri
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
// You can catch the exception here
}
}
}

I am unable to refer to things inside my activity, like buttons, and radiogroups

so I am trying to create an activity, and then add onclick listeners to it, but it wont let me refer. So the moment I open this activity in my app, my app crashes, saying 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference'
I have no idea why this is happening. I have correctly names them in accordance with the xml file as well.
Please help.
public class SubtaskActivity extends AppCompatActivity {
EditText etSubtaskName;
Button btnDone;
RadioGroup radgrpPri, radgrpTime;
RadioButton radbtnPriHigh, radbtnPriMed, radbtnPriLow, radbtnTimeMore, radbtnTimeMed, radbtnTimeLess;
boolean priHigh, priMed, priLow, timeMore, timeMed, timeLess;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnDone = findViewById(R.id.btnDone);
radgrpPri = findViewById(R.id.radgrpPri);
radgrpTime = findViewById(R.id.radgrpTime);
radbtnPriHigh = findViewById(R.id.radbtnPriHigh);
radbtnPriMed = findViewById(R.id.radbtnPriMed);
radbtnPriLow = findViewById(R.id.radbtnPriLow);
radbtnTimeMore = findViewById(R.id.radbtnTimeMore);
radbtnTimeMed = findViewById(R.id.radbtnTimeMed);
radbtnTimeLess = findViewById(R.id.radbtnTimeLess);
etSubtaskName = findViewById(R.id.etSubtaskName);
radgrpPri.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radbtnPriHigh.isChecked())
{
priHigh = true;
priLow = false;
priMed = false;
}
else if (radbtnPriMed.isChecked())
{
priHigh = false;
priLow = false;
priMed = true;
}
else if (radbtnPriLow.isChecked())
{
priHigh = false;
priLow = true;
priMed = false;
}
}
});
radgrpTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radbtnTimeMore.isChecked())
{
timeMore = true;
timeMed = false;
timeLess = false;
}
else if (radbtnTimeMed.isChecked())
{
timeMore = false;
timeMed = true;
timeLess = false;
}
else if (radbtnTimeLess.isChecked())
{
timeMore = false;
timeMed = false;
timeLess = true;
}
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = etSubtaskName.getText().toString().trim();
Intent intent = new Intent(SubtaskActivity.this, TaskInfo.class);
intent.putExtra("subtaskName", name);
intent.putExtra("priHigh", priHigh);
intent.putExtra("priMed", priMed);
intent.putExtra("priLow", priLow);
intent.putExtra("timeMore", timeMore);
intent.putExtra("timeMed", timeMed);
intent.putExtra("timeLess", timeLess);
startActivity(intent);
}
});
}
}
XML File :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/it"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:background="#color/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/background"
android:orientation="vertical">
<TextView
android:id="#+id/tvSubtaskPriorityHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/priority_of_subtask"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<RadioGroup
android:id="#+id/radgrpPri"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radbtnPriHigh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:buttonTint="#color/red"
android:text="#string/high"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnPriMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/yellow"
android:text="#string/medium"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnPriLow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/green"
android:text="#string/low"
android:textColor="#color/white" />
</RadioGroup>
<TextView
android:id="#+id/tvTimeWeightHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/time_this_subtask_may_consume"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_minutes"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etSubtaskName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/name_your_subtask"
android:inputType="textPersonName"
android:maxLength="20"
android:textColor="#color/white"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<RadioGroup
android:id="#+id/radgrpTime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radbtnTimeMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:buttonTint="#color/red"
android:text="#string/more"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnTimeMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/yellow"
android:text="#string/medium"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnTimeLess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/green"
android:text="#string/less"
android:textColor="#color/white" />
</RadioGroup>
</LinearLayout>
<Button
android:id="#+id/btnDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:gravity="center_horizontal"
android:text="#string/done"
app:backgroundTint="#color/orange_accent" />
</LinearLayout>
You didn't call in onCreate method setContentView(R.layout.youractivity). If you didn't, Android doesn't know what to render, so there are no views for you to provide.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youractivity);
}
just set your (xml)layout file to setContentView in onCreate()
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
}

Why won't a textView from a different layout file not properly run setText but textViews from activity_main will?

The program is supposed to run getCurrentLocation and then set the textView "coordinates" to the value of the coordinates called. That text view is part of a pager view that draws from a separate .xml file than the main layout "activity_main".
public class MainActivity extends AppCompatActivity
{
CardAdapter CardAdapter;
String coordinatesFinal;
FusedLocationProviderClient fusedLocationProviderClient;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
getCurrentLocation();
}else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
}
setupCardItems();
ViewPager2 CardViewPager = findViewById(R.id.cardViewPager);
CardViewPager.setAdapter(CardAdapter);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == 100 & grantResults.length > 0 && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED)
{
getCurrentLocation();
}else
{
Toast.makeText(getApplicationContext(), "Permission denied.",Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("MissingPermission")
public void getCurrentLocation()
{
coordinates = findViewById(R.id.coordinates);
LocationManager locationManager = (LocationManager) getSystemService
(
Context.LOCATION_SERVICE
);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task ->
{
Location location = task.getResult();
if (location != null)
{
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
}else
{
LocationRequest locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10000).setFastestInterval(1000).setNumUpdates(1);
LocationCallback locationCallback = new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult)
{
Location location1 = locationResult.getLastLocation();
coordinatesFinal = location1.getLatitude()+", "+location1.getLongitude();
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
}
});
}else
{
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
//card view
private void setupCardItems()
{
List<CardItem> CardItems = new ArrayList<>();
CardItem itemPageOne = new CardItem();
itemPageOne.setLocation("Home");
itemPageOne.setTemp("60°f");
itemPageOne.setWeatherDesc("Cloudy");
itemPageOne.setWeatherIcon(R.drawable.cloud);
itemPageOne.setHum("75%");
itemPageOne.setVis("10");
itemPageOne.setPrecip("50%");
itemPageOne.setDew("40°f");
itemPageOne.setCloud("80%");
itemPageOne.setFog("75%");
CardItem itemPageTwo = new CardItem();
itemPageTwo.setLocation("Madison");
itemPageTwo.setTemp("60°f");
itemPageTwo.setWeatherDesc("Sunny");
itemPageTwo.setWeatherIcon(R.drawable.sun);
itemPageTwo.setHum("75%");
itemPageTwo.setVis("10");
itemPageTwo.setPrecip("50%");
itemPageTwo.setDew("40°f");
itemPageTwo.setCloud("80%");
itemPageTwo.setFog("75%");
CardItem itemPageThree = new CardItem();
itemPageThree.setLocation("Milwaukee");
itemPageThree.setTemp("60°f");
itemPageThree.setWeatherDesc("Rainy");
itemPageThree.setWeatherIcon(R.drawable.rain);
itemPageThree.setHum("75%");
itemPageThree.setVis("10");
itemPageThree.setPrecip("50%");
itemPageThree.setDew("40°f");
itemPageThree.setCloud("80%");
itemPageThree.setFog("75%");
CardItems.add(itemPageOne);
CardItems.add(itemPageTwo);
CardItems.add(itemPageThree);
CardAdapter = new CardAdapter(CardItems);
}
}
I have narrowed it down to the line that doesn't work properly:
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
I have tested the exact same line as above, only using a textView from inside activity main, which works just fine. Any help is greatly appreciated.
Edit: The file actually does crash, I mistakenly said it didn't, and I added both .xml Files:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
android:background="#566D8F"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:paddingTop="15dp"
android:paddingBottom="15dp">
<ImageButton
android:id="#+id/settingsBar2"
android:layout_width="27sp"
android:layout_height="27sp"
android:layout_gravity="left"
android:layout_marginStart="20sp"
android:layout_marginEnd="70sp"
android:background="#color/background"
android:cropToPadding="true"
android:scaleType="fitCenter" />
<TextView
android:id="#+id/homeName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center_horizontal"
android:maxLines="1"
android:text="#string/app_name"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:typeface="normal" />
<ImageButton
android:id="#+id/settingsBar"
android:layout_width="27sp"
android:layout_height="27sp"
android:layout_gravity="right"
android:layout_marginStart="70sp"
android:layout_marginEnd="20sp"
android:background="#drawable/settings_handle"
android:cropToPadding="true"
android:scaleType="fitCenter" />
</LinearLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/cardViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="#+id/topBar" />
</androidx.constraintlayout.widget.ConstraintLayout>
item_container_card.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<androidx.cardview.widget.CardView
android:id="#+id/pagerCard"
android:layout_width="match_parent"
android:layout_height="440dp"
android:layout_margin="20dp"
app:cardBackgroundColor="#EAC0A0"
app:cardCornerRadius="30dp"
app:cardElevation="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/locationName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-medium"
android:gravity="center"
android:textColor="#color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/coordinates"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center"
android:textColor="#color/white"
android:textSize="12sp" />
<TextView
android:id="#+id/temperature"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:gravity="center"
android:textColor="#color/white"
android:textSize="50sp" />
<TextView
android:id="#+id/weatherDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center"
android:textColor="#color/white"
android:textSize="12sp" />
<ImageView
android:id="#+id/imageOnboarding"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_margin="15dp"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingBottom="5sp"
android:text="Humidity"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/humVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/visibility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingEnd="10sp"
android:paddingBottom="5sp"
android:text="Visibility"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/visVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingRight="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/precipitation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Precip. "
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/precipVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/dewPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Dew Point"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/dewVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingRight="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/cloud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Cloud"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/cloudVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/fog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Fog"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/fogVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Edit 2: CardAdapter.java and CardItem.java
CardAdapter.java:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder>
{
private List<CardItem> CardItems;
public CardAdapter(List<CardItem> CardItems) {
this.CardItems = CardItems;
}
#NonNull
#Override
public cardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new cardViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_card, parent, false
)
);
}
#Override
public void onBindViewHolder(#NonNull cardViewHolder holder, int position) {
holder.setCardData(CardItems.get(position));
}
#Override
public int getItemCount() {
return CardItems.size();
}
class cardViewHolder extends RecyclerView.ViewHolder
{
private TextView locationText;
private TextView weatherDesc;
private ImageView weatherIcon;
private TextView tempVal;
private TextView humVal;
private TextView visVal;
private TextView precipVal;
private TextView dewVal;
private TextView cloudVal;
private TextView fogVal;
public cardViewHolder(#NonNull View itemView)
{
super(itemView);
locationText = itemView.findViewById(R.id.locationName);
weatherDesc = itemView.findViewById(R.id.weatherDesc);
weatherIcon = itemView.findViewById(R.id.imageOnboarding);
tempVal = itemView.findViewById(R.id.temperature);
humVal = itemView.findViewById(R.id.humVal);
visVal = itemView.findViewById(R.id.visVal);
precipVal = itemView.findViewById(R.id.precipVal);
dewVal = itemView.findViewById(R.id.dewVal);
cloudVal = itemView.findViewById(R.id.cloudVal);
fogVal = itemView.findViewById(R.id.fogVal);
}
void setCardData(CardItem CardItem)
{
locationText.setText(CardItem.getLocation());
weatherDesc.setText(CardItem.getWeatherDesc());
weatherIcon.setImageResource(CardItem.getWeatherIcon());
tempVal.setText(CardItem.getTemp());
humVal.setText(CardItem.getHum());
visVal.setText(CardItem.getVis());
precipVal.setText(CardItem.getPrecip());
dewVal.setText(CardItem.getDew());
cloudVal.setText(CardItem.getCloud());
fogVal.setText(CardItem.getFog());
}
}
}
CardItem.java:
package com.example.viewpagertest;
public class CardItem
{
private int weatherIcon;
private String location;
private String temp;
private String weatherDesc;
private String hum;
private String vis;
private String precip;
private String dew;
private String cloud;
private String fog;
//weather icon
public int getWeatherIcon() {
return weatherIcon;
}
public void setWeatherIcon(int weatherIcon) {
this.weatherIcon = weatherIcon;
}
//location title
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
//temperature value
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
//weather description
public String getWeatherDesc() {
return weatherDesc;
}
public void setWeatherDesc(String weatherDesc) {
this.weatherDesc = weatherDesc;
}
//humidity value
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
//visibility value
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
//precipitation value
public String getPrecip() {
return precip;
}
public void setPrecip(String precip) {
this.precip = precip;
}
//dew point value
public String getDew() {
return dew;
}
public void setDew(String dew) {
this.dew = dew;
}
//cloud value
public String getCloud() {
return cloud;
}
public void setCloud(String cloud) {
this.cloud = cloud;
}
//fog value
public String getFog() {
return fog;
}
public void setFog(String fog) {
this.fog = fog;
}
}
Here's the Console when running a debugger with the breakpoint at
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
The whole console breaks the character limit so here's a document with the console text.
Console Text
if (location != null)
{
// coordinates.setText(location.getLatitude()+", "+location.getLongitude());
cardAdapter.setCoordinates(0 /*the cardItem number you want to update*/, location.getLatitude()+", "+location.getLongitude());
}
Since the coordinates TextView is in your item xml, you will not be able to address it from the root of your MainActivity, but from your item.
Update
Thanks for adding the Adapter code:
Easiest would be to create a method in your adapter like the following:
setCoordinates(int position, String coords) {
holders.get(position).itemView.findViewById(R.id.coordinates).setText(coords);
}
To be able to access the holders on runtime, add the following:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder>
{
private List<CardItem> cardItems;
private List<CardViewHolder> holders;
....
#Override
public cardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
CardViewHolder holder = new cardViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_card, parent, false
)
);
holders.add(holder);
return holder;
}
Another option would be to add the field coordinates to your CardItem and write the setCoordinates method like so:
setCoordinates(int position, String coords) {
cardItems.get(position).setCoordinates(coords);
notifyDataSetChanged(); // to reload the holders, only notifying the specific position will be faster to reload only the changed holder
}
You need to update the adapter items by creating a method in CardAdapter and calling it from main activity as below -
Create this method in your adapter class
public void updateAdapter(List<CardItem> CardItems) {
this.CardItems = CardItems;
notifyDataSetChanged();
}
Replace below line
CardAdapter = new CardAdapter(CardItems);
With this one
CardAdapter.updateAdapter(CardItems);

TextView cannot be cast to SeekBar

I am experiencing issues relating my textview to my seekbar, and have received the below message as such. I am under the premises that it was due for the following reasons: 1) Trying to store the seekbar values information recorded by the user into parse to be able to retrieve it later. Storing the EditText such as name, age, headline and radiobox such as gender works fine, but its when I include the seek that the application fails to run.
I have tried doing a project clean, and rewording ID with the "right prefix" such as sb for seekbar, and tv for textview.
Below is the logcat message:
update logcat posted below
Below is the activity code
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
RadioButton male, female;
String gender;
RadioButton lmale, lfemale;
String lgender;
protected SeekBar seekBarMinimum;
protected SeekBar seekBarMaximum;
protected SeekBar seekBarDistance;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
male = (RadioButton)findViewById(R.id.rimale);
female = (RadioButton)findViewById(R.id.rifemale);
lmale = (RadioButton)findViewById(R.id.rlmale);
lfemale = (RadioButton)findViewById(R.id.rlfemale);
seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
seekBarDistance = (SeekBar) findViewById(R.id.tvseekBarDistanceValue);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
seekBarMaximum.getProgress();
seekBarMinimum.getProgress();
seekBarDistance.getProgress();
if(male.isChecked())
gender = "Male";
else
gender = "Female";
if(lmale.isChecked())
lgender = "Male";
else
lgender = "Female";
currentUser.put("Name", name);
currentUser.put("Age", age);
currentUser.put("Headline", headline);
currentUser.put("Gender", gender);
currentUser.put("Looking_Gender", lgender);
currentUser.put("Minimum_Age", seekBarMinimum);
currentUser.put("Maximum_Age", seekBarMaximum);
currentUser.put("Maximum_Distance_Age", seekBarDistance);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.sbseekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.tvseekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tvMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tvMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Below is the layout xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollProfile"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/dark_texture_blue" >
<RelativeLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="797dp"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/profilePicturePreview"
android:layout_width="132dp"
android:layout_height="120dp"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="7dp"
android:layout_marginBottom="9dp"
android:padding="3dp"
android:scaleType="centerCrop"
android:cropToPadding="true"
android:background="#drawable/border_image"
android:alpha="1" />
<Button
android:id="#+id/bRemove"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_above="#+id/etxtage"
android:layout_alignLeft="#+id/etxtname"
android:alpha="0.8"
android:background="#330099"
android:text="Upload from Facebook"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnPictureSelect"
android:layout_width="118dp"
android:layout_height="60dp"
android:layout_alignRight="#+id/etxtname"
android:layout_below="#+id/profilePicturePreview"
android:layout_marginRight="8dp"
android:alpha="0.8"
android:background="#000000"
android:onClick="pickPhoto"
android:text="Select photo from gallery"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp"
android:text="Preferred Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:gravity="center"
android:text="Profile Creation"
android:textColor="#ffffff"
android:textSize="28sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtname"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true"
android:ems="10"
android:enabled="true"
android:hint="Please type your name here"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textSize="18sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtname"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="Upload your Profile Picture"
android:textColor="#f2f2f2"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_alignLeft="#+id/etxtheadline"
android:layout_height="wrap_content"
android:layout_below="#+id/texperience"
android:layout_toLeftOf="#+id/textView3" >
<RadioButton
android:id="#+id/rimale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/rifemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<SeekBar
android:id="#+id/sbseekBarDistance"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView12"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="50" />
<RadioGroup
android:id="#+id/radioGroup3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/radioGroup2"
android:layout_marginTop="10dp" >
</RadioGroup>
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/etxtheadline"
android:layout_below="#+id/textView2" >
<RadioButton
android:id="#+id/rlmale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/rlfemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<SeekBar
android:id="#+id/sbseekBarMinimumAge"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="25" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Minimum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tvseekBarDistanceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tvMinAge"
android:layout_below="#+id/sbseekBarDistance"
android:text="50"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f2f2f2"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Search Distance "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tvMinAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sbseekBarMinimumAge"
android:layout_centerHorizontal="true"
android:text="25"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvMaxAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Headline"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvMinAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Maximum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<SeekBar
android:id="#+id/sbseekBarMaximumAge"
android:layout_width="221dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView14"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="50" />
<TextView
android:id="#+id/tvMaxAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sbseekBarMaximumAge"
android:layout_centerHorizontal="true"
android:text="50"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/conditions"
android:layout_width="280dp"
android:layout_height="130dp"
android:layout_below="#+id/btnConfirm"
android:layout_centerHorizontal="true"
android:layout_marginBottom="7dp"
android:layout_marginTop="7dp"
android:alpha="0.6"
android:gravity="center"
android:text="#string/disclaimer"
android:textColor="#99CCFF"
android:textSize="12sp" />
<Button
android:id="#+id/btnConfirm"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/tvseekBarDistanceValue"
android:layout_marginBottom="7dp"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/tvseekBarDistanceValue"
android:alpha="0.8"
android:background="#151B54"
android:text="Confirm"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<EditText
android:id="#+id/etxtheadline"
android:layout_width="270dp"
android:layout_height="70dp"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:hint="A quick description of yourself"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etxtage"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/btnPictureSelect"
android:layout_marginTop="48dp"
android:ems="10"
android:hint="Please type your age here"
android:inputType="number"
android:maxLength="2"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/radioGroup1"
android:layout_alignRight="#+id/btnConfirm"
android:text="Looking for"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texperience"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_below="#+id/etxtheadline"
android:layout_marginTop="39dp"
android:text="I am a"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
/>
</RelativeLayout>
</ScrollView>
Any help would be greatly appreciated. All the best.
Update
Upon resolving the previous, another error related was triggered. I have tried resolving it, but is still experiencing issues. Below is the logcat
08-13 14:56:24.366: E/AndroidRuntime(1306): FATAL EXCEPTION: main
08-13 15:49:13.758: E/AndroidRuntime(1365): FATAL EXCEPTION: main
08-13 15:49:13.758: E/AndroidRuntime(1365): Process: com.dooba.beta, PID: 1365
08-13 15:49:13.758: E/AndroidRuntime(1365): java.lang.IllegalArgumentException: invalid type for value: class android.widget.SeekBar
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.parse.ParseObject.put(ParseObject.java:2152)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.parse.ParseUser.put(ParseUser.java:315)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.dooba.beta.ProfileCreation$1.onClick(ProfileCreation.java:136)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.view.View.performClick(View.java:4438)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.view.View$PerformClick.run(View.java:18422)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Handler.handleCallback(Handler.java:733)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Handler.dispatchMessage(Handler.java:95)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Looper.loop(Looper.java:136)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-13 15:49:13.758: E/AndroidRuntime(1365): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 15:49:13.758: E/AndroidRuntime(1365): at java.lang.reflect.Method.invoke(Method.java:515)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-13 15:49:13.758: E/AndroidRuntime(1365): at dalvik.system.NativeStart.main(Native Method)
Your XML has defined tvseekBarDistanceValue as a TextView, not a SeekBar. Since you're trying to change a TextView to a SeekBar (which is impossible), you are getting this error.
Based on your XML, I think you want to replace
seekBarDistance = (SeekBar) findViewById(R.id.tvseekBarDistanceValue);
with
seekBarDistance = (SeekBar) findViewById(R.id.sbseekBarDistance);

Categories