I am a beginner with Android Studio creating an app that will read from an API. I am trying to get the API to filter results using options chosen in two spinners; one option for a type of electric car charger and another for the max radius of results to be shown. The app suddenly crashes when it gets to the "if (defaultCharger.equals("0"))" statement. As there are no errors shown I have commented out different sections of code to see what works and this part seems to be the issue. This is here so the link will not include a filter for the charger type if one has not been chosen. Any help with this problem would be appreciated.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Spinner;
public class results extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String link, getLong, getLat;
TextView newAddress, see, testResult;
//Create spinner options
Spinner dropdownone, dropdowntwo;
String[] distance = {"Change the radius in miles", "1", "5", "10"};
String[] chargeType = {"Filter by type of charger", "Under 2kW", "Over 2kW", "40kW and higher"};
String defaultMiles, defaultCharger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
//text link to go back to home and enter a new address
newAddress = findViewById(R.id.newAddress);
newAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newAddress.setTextColor(getResources().getColorStateList(R.color.colorAccent));
Intent intent = new Intent(results.this, home.class);
startActivity(intent);
}
});
//get longitude and latitude
home home = new home();
if (home.status.equals("gps")){
getLong = home.gpsLong;
getLat = home.gpsLat;
}
else if (home.status.equals("address")){
GeoLocation geoLocation = new GeoLocation();
getLong = geoLocation.adLongitude;
getLat = geoLocation.adLatitude;
}
else {
getLong = "-5.926437";
getLat = "54.607868";
}
//drop down one - choose radius of results
dropdownone = findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(results.this,
android.R.layout.simple_spinner_item,distance);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdownone.setAdapter(adapter);
dropdownone.setOnItemSelectedListener(this);
//drop down two - choose charger type
dropdowntwo = findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(results.this,
android.R.layout.simple_spinner_item,chargeType);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdowntwo.setAdapter(adapter2);
dropdowntwo.setOnItemSelectedListener(this);
//see if correct values are being returned
see = findViewById(R.id.textView6);
see.setText(defaultMiles + " " + defaultCharger);
//create link
if (defaultCharger.equals("0")){
link = "https://api.openchargemap.io/v3/poi/?output=json&Latitude=" + getLat + "&Longitude=" + getLong + "&distance=" + defaultMiles + "&distanceunit=miles&maxresults=10&compact=true&verbose=false";
}
else {
link = "https://api.openchargemap.io/v3/poi/?output=json&Latitude=" + getLat + "&Longitude=" + getLong + "&distance=" + defaultMiles + "&distanceunit=miles&LevelID=" + defaultCharger + "&maxresults=1&compact=true&verbose=false";
}
testResult = findViewById(R.id.testResult);
testResult.setText(link);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
switch (parent.getId()){
case R.id.spinner1:
switch (position) {
case 0:
// Create default if nothing is changed
defaultMiles = "0";
break;
case 1:
// 1 mile radius
defaultMiles = "1";
break;
case 2:
// 5 mile radius
defaultMiles = "5";
break;
case 3:
// 10 mile radius
defaultMiles = "10";
break;
}
case R.id.spinner2:
switch (position) {
case 0:
// Default for no charger filter
defaultCharger = "0";
break;
case 1:
// Type 1 charger
defaultCharger = "1";
break;
case 2:
// Type 2 charger
defaultCharger = "2";
break;
case 3:
// Type 3 charger
defaultCharger = "3";
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
defaultMiles = "10";
defaultCharger = "0";
}
}
Your defaultCharger String will be null in the onCreate method, causing a NullPointerException when trying to compare it : if (defaultCharger.equals("0")) .
You can prevent it by setting a value like "" for defaultCharger during variable declaration:
String defaultCharger = "";
or by switching around the equals statement:
if ("0".equals(defaultCharger))
Related
I know setText just changes the text only once but I can't seem to find the reason why the text in it changes before I move on to the next question in the quizActivity
What I have made is an app with one activity in it which has a quiz in it, a question is displayed along with 4 options. When the user selects an option, if that option is correct then it becomes green and red otherwise and additionally, I then open a dialog box showing whether the answer was right or wrong and then the question is changed when the user clicks Next on the dialog box.
But what is happening that when the user selects an option, in between the process of clicking the option and then clicking next on the dialog box, the text in the questions and the options changes and I can't seem to figure out why is that happening. In total, the question and options change two times when they should change only once, the unexpected change is when the user clicks on an option and the dialog box opens.
Here's the code:
#Override
public void onClick(View view) {
int selectedOption = 0;
switch (view.getId()) {
case R.id.option_1_tile:
selectedOption = 1;
break;
case R.id.option_2_tile:
selectedOption = 2;
break;
case R.id.option_3_tile:
selectedOption = 3;
break;
case R.id.option_4_tile:
selectedOption = 4;
break;
default:
}
checkAnswer(selectedOption, view);
}
Here's the function which checks the answer:
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == selected_questions.get(quesNum).getAnswer()) {
//Right Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
quizReference.child(selected_questions.get(quesNum).getId()).child("correct_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getCorrect_attempts()) + 1));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
score++;
correctDialog();
} else {
//Wrong Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
switch (selected_questions.get(quesNum).getAnswer()) {
case 1:
options[0].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
options[1].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
options[2].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
options[3].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
wrongDialog ();
}
}
Here's the function which changes the question:
private void changeQuestion() {
resetColor ();
if (quesNum < selected_questions.size() - 1) {
quesNum++;
playAnim(question, 0, 0);
playAnim(option1_text, 0, 1);
playAnim(option2_text, 0, 2);
playAnim(option3_text, 0, 3);
playAnim(option4_text, 0, 4);
qCount.setText(String.valueOf(quesNum + 1) + "/" + String.valueOf(selected_questions.size()));
} else {
// Go to Score Activity
Intent intent = new Intent(quizActivity.this, scoreActivity.class);
intent.putExtra("SCORE", String.valueOf(score) + "/" + String.valueOf(selected_questions.size()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Here's the function which sets the text and animation:
private void playAnim(final View view, final int value, final int viewNum) {
view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500)
.setStartDelay(100).setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
if (value == 0) {
switch (viewNum) {
case 0:
((TextView) view).setText(selected_questions.get(quesNum).getQuestion());
break;
case 1:
((TextView) view).setText(selected_questions.get(quesNum).getOption1());
break;
case 2:
((TextView) view).setText(selected_questions.get(quesNum).getOption2());
break;
case 3:
((TextView) view).setText(selected_questions.get(quesNum).getOption3());
break;
case 4:
((TextView) view).setText(selected_questions.get(quesNum).getOption4());
break;
}
if (viewNum != 0)
(view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#E99C03")));
playAnim(view, 1, viewNum);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
Here's the code for the dialog boxes:
public void wrongDialog() {
final Dialog dialogWrong = new Dialog(quizActivity.this);
dialogWrong.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogWrong.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogWrong.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogWrong.setContentView(R.layout.dialog_wrong);
dialogWrong.setCancelable(false);
dialogWrong.show();
TextView wrongText = (TextView) dialogWrong.findViewById(R.id.wrongText);
Button buttonNext = (Button) dialogWrong.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogWrong.dismiss();
//reset the color of buttons back to white
resetColor();
//Change question
changeQuestion();
}
});
}
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(quizActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
Button buttonNext = (Button) dialogCorrect.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//reset the color of buttons back to white
resetColor();
//it will increment the question number
changeQuestion();
}
});
}
I have tried to explain it to my best ability though I would be glad to answer any additional information/code you may want. Also, this is the link for the project if you have the time to run it and understand the problem better.
I have checked your code. you have placed an addValueEventListener in setUpdates method. When you select an option, you update the firestore database by setting fields like total attempts. As a result, eventListener gets triggered and "selectQuestionSet" function is called.
Hence, every time you select an option, selectQuestionSet function is called. You should make sure that its called only once at the start.
I'm new to android development and I am creating an android application that works like "4 Pics 1 Word" for my project. I'm having difficulties in storing ArrayList in SharedPreferences or in the internal storage of the android phone. The reason why is because I am randomizing the next activity using random generator and ArrayList. Any suggestions or ideas that my help my case? Thank you in advance! I've been stuck here for hours now.
This is my MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnStart;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(first.class);
activityList.add(second.class);
activityList.add(third.class);
activityList.add(fourth.class);
activityList.add(fifth.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
activity = first.class;
// We are adding the number of the activity to the list
activityList.remove(first.class);
break;
case 2:
activity = second.class;
activityList.remove(second.class);
break;
case 3:
activity = third.class;
activityList.remove(third.class);
break;
case 4:
activity = fourth.class;
activityList.remove(fourth.class);
break;
default:
activity = fifth.class;
activityList.remove(fifth.class);
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
// `intent.putExtra(...)` is used to pass on extra information to the next activity
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
}
And here's my first activity:
public class first extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etAnswer = (EditText) findViewById(R.id.etAnswer);
btnGo = (Button) findViewById(R.id.btnGo);
btnGo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnGo:
String answer = etAnswer.getText().toString();
if(answer.equals("Jose Rizal") || answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal") ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
"Source: http://www.joserizal.ph/ta01.html");
dlgAlert.setTitle("Did you know that ...");
dlgAlert.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
Context context = getApplicationContext();
CharSequence last = "Congratulations! You just finished the game! Please wait for the next update!";
int durationFinal = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, last, durationFinal);
toast.show();
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}else{
Context context = getApplicationContext();
CharSequence text = "Wrong! Try Again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
}
}
}
Okay, this is a horrible hack and I don't endorse it in any way, but since you are so close to finishing your app, I propose a workaround:
Instead of storing an ArrayList<Class> in your SharedPreferences (which is impossible), store a HashSet<String> containing the fully qualified names of your classes via putStringSet().
In order to get the String representations of the fully qualified names of your classes you need to call getName(), e.g. first.class.getName().
Then, you can get your Set<String> from SharedPreferences using getStringSet() and create a Class instance for each String in that set via Class.forName().
I'm making a Quizz App for Android with 10 Questions, all of them with 4 Radio Buttons, and one button at the end to show the score. The problem is when I choose the correct answer it gives 5 points, but if I check another radio button the points will stay 5 and if I press again it sums 5. What is the best way to code this?
Here is the code:
package com.example.android.quizproject;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
points += 0;
break;
case R.id.questionOneB:
if (checked)
points += 0;
break;
case R.id.questionOneC:
if (checked)
points += 5;
break;
case R.id.questionOneD:
if (checked)
points += 0;
break;
}
}
public void showScore (View view) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(" " + points);
}
}
You can make use of a counter vvariable which checks if the question has been previousy answered or not. Modify part of your code to this
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
int count=0;
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneB:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneC:
if (checked){
points += 5;
count+=1;}
break;
case R.id.questionOneD:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
}
}
Actually, the way you described it, it's common sense. If you click the right answer once, it will set it to 5, but if you press any other it will add 0 to it.
In general, it will print out 5 since you got the answer correct once, and the other questions are set to 0. There's really nothing to fix here, it's kind of common sense that your variable wouldn't read other than 5. Just like Abhriya said, you could add a counter increment value as done in ( her / his ) example.
This application, displays an EEG devices OSC data. So far it can display the it receives from the device.
#Override
public void receiveDataPacket(DataPacket p) {
switch (p.getPacketType()) {
case EEG:
updateEeg(p.getValues());
break;
case ACCELEROMETER:
updateAccelerometer(p.getValues());
break;
case ALPHA_RELATIVE:
updateAlphaRelative(p.getValues());
break;
case BATTERY:
fileWriter.addDataPacket(1, p);
// It's library client responsibility to flush the buffer,
// otherwise you may get memory overflow.
if (fileWriter.getBufferedMessagesSize() > 8096)
fileWriter.flush();
break;
default:
break;
}
}
private void updateEeg(final ArrayList<Double> data) {
Activity activity = activityRef.get();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tp9 = (TextView) findViewById(R.id.eeg_tp9);
TextView fp1 = (TextView) findViewById(R.id.eeg_fp1);
TextView fp2 = (TextView) findViewById(R.id.eeg_fp2);
TextView tp10 = (TextView) findViewById(R.id.eeg_tp10);
tp9.setText(String.format(
"%6.2f", data.get(Eeg.TP9.ordinal())));
fp1.setText(String.format(
"%6.2f", data.get(Eeg.FP1.ordinal())));
fp2.setText(String.format(
"%6.2f", data.get(Eeg.FP2.ordinal())));
tp10.setText(String.format(
"%6.2f", data.get(Eeg.TP10.ordinal())));
}
});
}
}
I would like to create an array that holds and records the EEG values from the different positions. I would like to populate this list and enable a button that can display a graphical representation of the data.
Could i create an array and populate it as followed in the recieveDataPacket(Datapacket p) case EEG? My problem the data is being updated via a refresh function, which refreshes it and gets the new data. There are 4 positions and i would like to atleast have 5-10 values from each position in an array to populate the line graph.
EEGData[] eegData = new EEGData[]
for(int i = 0; i<eegData.length; i++){
eegData[i] = new EEGData();}
refresh function:
public void onClick(View v) {
Spinner Spinner = (Spinner) findViewById(R.id.spinner);
if (v.getId() == R.id.refresh) {
MuManager.refreshPaired();
List<Device> pairedDevice = MManager.getPaired();
List<String> spinnerItems = new ArrayList<String>();
for (Device m: pairedDevice) {
String dev_id = m.getName() + "-" + m.getMacAddress();
Log.i("Device", dev_id);
spinnerItems.add(dev_id);
}
ArrayAdapter<String> adapterArray = new ArrayAdapter<String> (
this, android.R.layout.simple_spinner_item, spinnerItems);
Spinner.setAdapter(adapterArray);
}
I know that the data is constantly varrying, could i keep a counter for the first 15 values for each position then populate an array which the graph can pull data from.
I have a TextView[] object and a String[] field in a Fragment. I have 5 Fragments in total, all handled by a ViewPager. I want to retrieve pretty much all of the Strings displayed in each Fragment (and save it to a text file later) from the click of the parent activity's menu.
Anyway, here is some code:
This is within the main Activity (only working on retrieving data from first fragment):
private Intent createShareIntent() {
DisplayFragment displayFragment = (DisplayFragment) mAdapter.getItem(2);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide what to do
// with it.
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Display Info");
shareIntent.putExtra(Intent.EXTRA_TEXT, displayFragment.retrieveContent());
return shareIntent;
}
The NullPointerException comes from this method within DisplayFragment:
public class DisplayFragment extends Fragment {
static String devDensity, devDensityCategory, devDpi, devXDpi, devYDpi,
devPxWidth, devPxHeight, devRefreshRate, devOrientation;
static TextView tvDispDensity, tvDensityCategory, tvDispDpi, tvDispXDpi,
tvDispYDpi, tvDispPxWidth, tvDispPxHeight, tvDispRefreshRate,
tvOrientation;
DisplayMetrics metrics;
// For sharing information via e-mail/SMS
/**
* Final Content of display info
*/
String displayInfoContent;
/**
* All textviews used in for-loop to getText()
*/
private TextView[] textViews;
private String[] strings;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.display, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay()
.getMetrics(metrics);
devDensity = String.valueOf(metrics.density);
devDpi = String.valueOf(metrics.densityDpi);
devXDpi = String.valueOf(metrics.xdpi);
devYDpi = String.valueOf(metrics.ydpi);
devPxWidth = String.valueOf(metrics.widthPixels);
devPxHeight = String.valueOf(metrics.heightPixels);
devRefreshRate = String.valueOf(getActivity().getWindowManager()
.getDefaultDisplay().getRefreshRate());
translate();
// Displays
tvDispDensity = (TextView) getView()
.findViewById(R.id.tvDisplayDensity);
tvDispDensity.setText(devDensity);
tvDensityCategory = (TextView) getView().findViewById(
R.id.tvDensityCategory);
tvDensityCategory.setText(devDensityCategory);
tvDispDpi = (TextView) getView().findViewById(R.id.tvDisplayDpi);
tvDispDpi.setText(devDpi);
tvDispXDpi = (TextView) getView().findViewById(R.id.tvDisplayXDpi);
tvDispXDpi.setText(devXDpi);
tvDispYDpi = (TextView) getView().findViewById(R.id.tvDisplayYDpi);
tvDispYDpi.setText(devYDpi);
tvDispPxWidth = (TextView) getView()
.findViewById(R.id.tvDisplayWidthPx);
tvDispPxWidth.setText(devPxWidth + " px");
tvDispPxHeight = (TextView) getView().findViewById(
R.id.tvDisplayHeightPx);
tvDispPxHeight.setText(devPxHeight + " px");
tvDispRefreshRate = (TextView) getView().findViewById(
R.id.tvDisplayRefreshRate);
tvDispRefreshRate.setText(devRefreshRate + " Hz");
tvOrientation = (TextView) getView().findViewById(
R.id.tvDisplayOrientation);
tvOrientation.setText(devOrientation);
//
// #################################
textViews = new TextView[]{tvDispDensity, tvDensityCategory, tvDispDpi, tvDispXDpi,
tvDispYDpi, tvDispPxWidth, tvDispPxHeight, tvDispRefreshRate,
tvOrientation};
strings = new String[]{devDensity, devDensityCategory, devDpi, devXDpi, devYDpi,
devPxWidth, devPxHeight, devRefreshRate, devOrientation};
}
private void translate() {
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
devDensityCategory = "Low (120 dpi)";
break;
case DisplayMetrics.DENSITY_MEDIUM:
devDensityCategory = "Medium (160 dpi)";
break;
case DisplayMetrics.DENSITY_HIGH:
devDensityCategory = "High (240 dpi)";
break;
case DisplayMetrics.DENSITY_XHIGH:
devDensityCategory = "XHigh (320 dpi)";
break;
case DisplayMetrics.DENSITY_XXHIGH:
devDensityCategory = "XXHigh (480 dpi)";
break;
case DisplayMetrics.DENSITY_XXXHIGH:
devDensityCategory = "XXXHigh (640 dpi)";
break;
case DisplayMetrics.DENSITY_TV:
devDensityCategory = "TV (213 dpi)";
break;
case DisplayMetrics.DENSITY_400:
devDensityCategory = "Intermediate (400 dpi)";
break;
default:
devDensityCategory = "Unknown";
break;
}
switch (getActivity().getWindowManager().getDefaultDisplay()
.getRotation()) {
case Surface.ROTATION_0:
devOrientation = "0°";
break;
case Surface.ROTATION_90:
devOrientation = "90°";
break;
case Surface.ROTATION_180:
devOrientation = "180°";
break;
case Surface.ROTATION_270:
devOrientation = "270°";
break;
default:
devOrientation = "Unknown";
break;
}
}
public String retrieveContent() {
String content = "";
for (int i = 0; i < textViews.length; i++) {
content += (textViews[i].getText() + " = " + strings[i] + "\n");
}
return content;
}
Are the Arrays initialized when the Fragment is off-screen? If not, how could I pull this off otherwise?
Logcat:
java.lang.NullPointerException
at my.package.name.fragments.DisplayFragment.retrieveContent(DisplayFragment.java:170)
which is this content += (textViews[i].getText() + " = " + strings[i] + "\n"); in my for loop.
Any insight will be greatly appreciated, thank you for reading.
Regards,
Matt
Are the Arrays initialized when the Fragment is off-screen? If not, how could I pull this off otherwise?
The problem is when the Fragment is off-screen, the fragment itself might not have been created at all. By default, the view pager only initialize the previous and next page of the current page. For example, if you are active on page 1, only page 2 will be initialized by default. if you are on third page, then only 2nd, 3rd and 4th pages are created.
To pull this of otherwise? you can just simply set the off screen page limit to 4, so that it will make sure that it will keep 4 pages next or previous of your current page (in your case, all 5 fragments will be created at once)
urViewPager.setOffscreenPageLimit(4);
put that code in the OnCreate on the activity after your initialization of urViewPager.
Hope this helps, cheer.
I found the culprit. Apparently the TextView[] was not initialized properly. Insted of having it in OnActivityCreated(), I initialized TextView[] and String[] directly in retrieveInfo() method of fragment. Also made textview fields static variables and works like a charm
public String retrieveContent() {
textViews = new TextView[]{tvDispDensity, tvDensityCategory, tvDispDpi, tvDispXDpi,
tvDispYDpi, tvDispPxWidth, tvDispPxHeight, tvDispRefreshRate,
tvOrientation};
strings = new String[]{devDensity, devDensityCategory, devDpi, devXDpi, devYDpi,
devPxWidth, devPxHeight, devRefreshRate, devOrientation};
String content = "";
for (int i = 0; i < textViews.length; i++) {
content += (textViews[i].getText() + " = " + strings[i] + "\n");
}
return content;
}
Works just fine now :)