I have a code to check PNR number. Because of internet issues, i thought to give users to check PNR by SMS. So I added 2 Radio Buttons, one for internet and one for SMS. But the problem is now when I click the PNR Button, it gives nullPointer Exception.
Here is my Main Activity.java
public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private EditText pnrNumber;
private TextView errMsg;
private Button getPnr;
private Button pnrClear;
Button Yes, No;
RadioButton checkbyinternet, checkbysms;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
errMsg = (TextView) findViewById(R.id.errMsg);
pnrNumber = (EditText) findViewById(R.id.pnrNumber_p01);
getPnr = (Button) findViewById(R.id.checkPNRButton);
pnrClear = (Button) findViewById(R.id.pnrClear);
getPnr.setOnClickListener(this);
pnrClear.setOnClickListener(this);
}
public void onClick(View src) {
// Perform action on click
if (src.getId() == R.id.checkPNRButton)
{
if (checkbyinternet.isChecked())
{
int pnr2 = pnrNumber.getEditableText().length();
if (pnr2 != 10)
{
errMsg.setText("Length of PNR is Invalid.");
}
else
{
String pnr = pnrNumber.getEditableText().toString();
Bundle b = new Bundle();
b.putString("pnr", pnr);
System.out.println("Connectivity : "
+ this.isNetworkAvailable());
PNRStatus pnrStatus = null;
// Connect to the Server and Get the PNR status
try
{
String captcha = "37819";
String pnr1 = pnrNumber.getText().toString();
String reqStr = "lccp_pnrno1=" + pnr1
+ "&lccp_cap_val=" + captcha
+ "&lccp_capinp_val=" + captcha
+ "&submitpnr=Get+Status";
PNRStatusCheck check = new PNRStatusCheck();
StringBuffer data = check
.getPNRResponse(reqStr,
"http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi_28688.cgi");
// String pnr1 = pnr; //"1154177041";
// String reqStr = "lccp_pnrno1=" + pnr1 +
// "&submitpnr=Get+Status";
// PNRStatusCheck check = new PNRStatusCheck();
// StringBuffer data = check.getPNRResponse(reqStr,
// "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi");
if (data != null)
{
pnrStatus = check.parseHtml(data);
b.putSerializable("pnrStatus", pnrStatus);
}
else
{
// error
}
}
catch (Exception e)
{
e.printStackTrace();
}
Intent to = null;
if (pnrStatus != null)
{
to = new Intent(this, PNRStatusActivity.class);
to.putExtras(b);
startActivity(to);
}
else
{
errMsg.setText("Error prcessing PNR. Please try again.");
}
}
}
else if (checkbysms.isChecked())
{
// Toast.makeText(this, "SMS", Toast.LENGTH_SHORT).show();
int pnr2 = pnrNumber.getEditableText().length();
if (pnr2 != 10)
{
errMsg.setText("Length of PNR is Invalid.");
}
else
{
openSMSWarningDialog(src);
}
}
}
else if (src.getId() == R.id.pnrClear)
{
errMsg.setText("");
pnrNumber.setText("");
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public void openSMSWarningDialog(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.smsdialog);
dialog.setTitle("Are you sure to use SMS.?");
Yes = (Button) dialog.findViewById(R.id.yes);
No = (Button) dialog.findViewById(R.id.no);
Yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String PnrNum = pnrNumber.getText().toString();
String messageToSend = ("PNR " + PnrNum);
String number = "139";
SmsManager.getDefault().sendTextMessage(number, null,
messageToSend, null, null);
dialog.dismiss();
Toast.makeText(
getBaseContext(),
"Please check your inbox in sometime for your PNR Status",
Toast.LENGTH_LONG).show();
}
});
No.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
}
And here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:background="#drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:text="#string/title"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/errMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:textColor="#android:color/black"
android:text="10 Digits Mandatory" />
<EditText
android:id="#+id/pnrNumber_p01"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:paddingLeft="10dp"
android:background="#drawable/edittextellipsedbackground"
android:layout_marginTop="17dp"
android:layout_marginBottom="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:hint="#string/pnrTextView" >
<requestFocus />
</EditText>
<Button
android:id="#+id/checkPNRButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/bluebutton"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:padding="10dp"
android:shadowColor="#000000"
android:shadowRadius="5.9"
android:text="#string/checkPNRButton"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="#+id/pnrClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bluebutton"
android:layout_marginTop="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:padding="10dp"
android:shadowColor="#000000"
android:shadowRadius="5.9"
android:text="Clear"
android:textColor="#ffffff"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="20dp"
android:background="#drawable/roundlayoutborder"
android:gravity="center"
android:paddingBottom="5dp" >
<RadioGroup
android:id="#+id/checkvia"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:orientation="vertical" >
<RadioButton
android:id="#+id/internet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#android:color/black"
android:text="#string/CheckByInternet"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RadioButton
android:id="#+id/sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:text="#string/CheckBySMS"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
</LinearLayout>
</LinearLayout>
SMS Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9bafb0"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textColor="#ff0000"
android:ems="27"
android:text="#string/CheckThroughSMSWarning" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp" >
<Button
android:id="#+id/yes"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="2dp"
android:textColor="#android:color/white"
android:layout_weight="1"
android:background="#drawable/bluebutton"
android:text="Yes" />
<Button
android:id="#+id/no"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="5dp"
android:textColor="#android:color/white"
android:layout_weight="1"
android:background="#drawable/bluebutton"
android:text="No" />
</LinearLayout>
</LinearLayout>
Here is my LOG:
02-06 13:54:22.810: E/AndroidRuntime(858): FATAL EXCEPTION: main
02-06 13:54:22.810: E/AndroidRuntime(858): java.lang.NullPointerException
02-06 13:54:22.810: E/AndroidRuntime(858): at akshat.jaiswal.indianrailways.MainActivity.onClick(MainActivity.java:50)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4084)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:16966)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:615)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-06 13:54:22.810: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 13:54:22.810: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 13:54:22.810: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-06 13:54:22.810: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-06 13:54:22.810: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
Please help, I am not able to get any solution for this.
Your checkbyinternet and checkbysms buttons are uninitialized and that is why you're getting the NullPointerException when if (checkbyinternet.isChecked()) is executed in the onClick() method.
if (src.getId() == R.id.checkPNRButton) // true if you pressed the getPnr button
{
if (checkbyinternet.isChecked()) // checkbyinternet is uninitialized yet, so it'll throw a NPE
You need to initialize them as well in the onCreate() method.
checkbyinternet = (RadioButton) findViewById(R.id.internet);
checkbysms = (RadioButton) findViewById(R.id.sms);
Related
I am a newbie trying to create a simple quiz app in Android Studio. Things were progressing reasonably well until I tried to create an onClick event for a radiogroup.
I took a look at this previously answered question: java.lang.IllegalStateException: Could not execute method for android:onClick Android App but the solution did not shed any light on my issue.
Another thing I noticed was a problem with the imported AppCompatViewInflater.java WHICH 'cannot resolve symbol 'R''?
Any advice would much appreciated.
This is the logcat error message that I see:
02-05 09:19:16.989 29473-29473/com.example.hughdavidson_quizapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hughdavidson_quizapp, PID: 29473
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:5205)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:21164)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:5205)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:21164)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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: android.content.res.Resources$NotFoundException: Resource ID #0x7f0c0004
This is the MainActivity.java code
///
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroupQ1;
ImageView q1ImageView;
TextView textViewQ2;
ImageView q2ImageView;
CheckBox checkBoxQ3_i, checkBoxQ3_ii, checkBoxQ3_iii, checkBoxQ3_iv, checkBoxQ3_v;
ImageView q3_i_ImageView, q3_ii_ImageView, q3_iii_ImageView, q3_iv_ImageView, q3_v_ImageView;
boolean hasCheckBoxQ3_i = false;
boolean hasCheckBoxQ3_ii = false;
boolean hasCheckBoxQ3_iii = false;
boolean hasCheckBoxQ3_iv = false;
boolean hasCheckBoxQ3_v = false;
EditText editTextQ4_i_Answer, editTextQ4_ii_Answer, editTextQ4_iii_Answer, editTextQ4_iv_Answer;
ImageView q4_i_ImageView, q4_ii_ImageView, q4_iii_ImageView, q4_iv_ImageView;
int userScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Ref for working with radiogroups: https://stackoverflow.com/questions/9748070/radio-group-onclick-event-not-firing-how-do-i-tell-which-is-selected
radioGroupQ1 = (RadioGroup) findViewById(R.id.q1_radio_buttons);
radioGroupQ1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.q1_radioButton_false:
userScore += + 0;
q1ImageView.setImageResource(R.mipmap.red_cross);
break;
case R.id.q1_radioButton_true:
userScore += + 1;
q1ImageView.setImageResource(R.mipmap.green_tick);
break;
}
}
});
textViewQ2 = (TextView) findViewById(R.id.q2_editText);
checkBoxQ3_i = (CheckBox) findViewById(R.id.checkBoxQ3_i) ;
checkBoxQ3_ii = (CheckBox) findViewById(R.id.checkBoxQ3_ii) ;
checkBoxQ3_iii = (CheckBox) findViewById(R.id.checkBoxQ3_iii) ;
checkBoxQ3_iv = (CheckBox) findViewById(R.id.checkBoxQ3_iv) ;
checkBoxQ3_v = (CheckBox) findViewById(R.id.checkBoxQ3_v) ;
editTextQ4_i_Answer = (EditText) findViewById(R.id.q4_i_editBox);
editTextQ4_ii_Answer = (EditText) findViewById(R.id.q4_ii_editBox);
editTextQ4_iii_Answer = (EditText) findViewById(R.id.q4_iii_editBox);
editTextQ4_iv_Answer = (EditText) findViewById(R.id.q4_iv_editBox);
q1ImageView = (ImageView) findViewById(R.id.q1_redcross_image_view);
q2ImageView = (ImageView) findViewById(R.id.q2_redgreencheck_image_view);
q3_i_ImageView = (ImageView) findViewById(R.id.q3_i_greencheck_image_view);
q3_ii_ImageView = (ImageView) findViewById(R.id.q3_ii_greencheck_image_view);
q3_iii_ImageView = (ImageView) findViewById(R.id.q3_iii_redcheck_image_view);
q3_iv_ImageView = (ImageView) findViewById(R.id.q3_iv_greencheck_image_view);
q3_v_ImageView = (ImageView) findViewById(R.id.q3_v_greencheck_image_view);
q4_i_ImageView = (ImageView) findViewById(R.id.q4_i_redgreencheck_image_view);
q4_ii_ImageView = (ImageView) findViewById(R.id.q4_ii_redgreencheck_image_view);
q4_iii_ImageView = (ImageView) findViewById(R.id.q4_iii_redgreencheck_image_view);
q4_iv_ImageView = (ImageView) findViewById(R.id.q4_iv_redgreencheck_image_view);
}
//Show users total score
public void showScore(View view){
//Check score for question 1
//Check score for question 2
String q2Answer = "1000000";
if (textViewQ2.getText().toString().equals(q2Answer)){
userScore = userScore + 1;
q2ImageView.setImageResource(R.mipmap.green_tick);
}
else q2ImageView.setImageResource(R.mipmap.red_cross);
//check score for question 3
//has Q3-i been ticked
hasCheckBoxQ3_i = checkBoxQ3_i.isChecked();
//has Q3-ii been ticked
hasCheckBoxQ3_ii = checkBoxQ3_ii.isChecked();
//has Q3-iii been ticked
hasCheckBoxQ3_iii = checkBoxQ3_iii.isChecked();
//has Q3-iv been ticked
hasCheckBoxQ3_iv = checkBoxQ3_iv.isChecked();
//has Q3-v been ticked
hasCheckBoxQ3_v = checkBoxQ3_i.isChecked();
if(hasCheckBoxQ3_i){
userScore += +1;
q3_i_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_ii){
userScore += +1;
q3_ii_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_iii){
userScore += +1;
q3_iii_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_iv){
userScore += +1;
q3_iv_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_v){
userScore += +0;
q3_v_ImageView.setImageResource(R.mipmap.red_cross);
}
//Check score for Q4
//Reference: string comparison https://stackoverflow.com/questions/16143562/string-comparison-android/16143606#:~:text=The%20%3D%3D%20operator%20checks%20to,to%20compare%20strings%20for%20equality.
String Q4_i = "E";
String Q4_ii = "A";
String Q4_iii = "C";
String Q4_iv = "B";
if(editTextQ4_i_Answer.getText().toString().equals(Q4_i)){
userScore += +1;
q4_i_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_i_ImageView.setImageResource(R.mipmap.red_cross);
if(editTextQ4_ii_Answer.getText().toString().equals(Q4_ii)){
userScore += +1;
q4_ii_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_ii_ImageView.setImageResource(R.mipmap.red_cross);
if(editTextQ4_iii_Answer.getText().toString().equals(Q4_iii)){
userScore += +1;
q4_iii_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_iii_ImageView.setImageResource(R.mipmap.red_cross);
if(editTextQ4_iv_Answer.getText().toString().equals(Q4_iv)){
userScore += +1;
q4_iv_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_iv_ImageView.setImageResource(R.mipmap.red_cross);
// Toast message to user with score
Context context = getApplicationContext();
CharSequence text = "You scored: " + userScore + " out of 11";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
...
}
///
and this is the XML:
///
<?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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/q1"
style="#style/QuestionLabel"
android:text="#string/q1" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<TextView
android:id="#+id/q1_text"
style="#style/QuestionText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/q1_text"/>
<RadioGroup
android:id="#+id/q1_radio_buttons"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q1_text">
<RadioButton
android:id="#+id/q1_radioButton_false"
android:text="#string/q1_radio_button_false"/>
<RadioButton
android:id="#+id/q1_radioButton_true"
android:text="#string/q1_radio_button_true"/>
</RadioGroup>
<TextView
android:id="#+id/q2"
style="#style/QuestionLabel"
android:text="#string/q2"/>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="100dp" />
<TextView
android:id="#+id/q2_text"
style="#style/QuestionText"
android:text="#string/q2_text" />
<EditText
android:id="#+id/q2_editText"
android:hint="#string/user_hint"
android:importantForAutofill="no"
android:inputType="number|text" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="176dp" />
<TextView
android:id="#+id/q3"
style="#style/QuestionLabel"
android:text="#string/q3" />
<TextView
android:id="#+id/q3_text"
style="#style/QuestionText"
android:text="#string/q3_text" />
<CheckBox
android:id="#+id/checkBoxQ3_i"
style="#style/CheckBox"
android:checked="false"
android:text="#string/q3_i" />
<CheckBox
android:id="#+id/checkBoxQ3_ii"
style="#style/CheckBox"
android:checked="false"
android:text="#string/q3_ii" />
<CheckBox
android:id="#+id/checkBoxQ3_iii"
style="#style/CheckBox"
android:checked="false"
android:text="#string/q3_iii" />
<CheckBox
android:id="#+id/checkBoxQ3_iv"
style="#style/CheckBox"/>
<CheckBox
android:id="#+id/checkBoxQ3_v"
style="#style/CheckBox"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="70dp"
android:layout_marginRight="70dp"
android:checked="false"
android:text="#string/q3_v" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="180dp" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="326dp" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="316dp" />
<TextView
android:id="#+id/q4"
style="#style/QuestionLabel"
android:text="#string/q4"
app:layout_constraintEnd_toStartOf="#+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<ImageView
android:id="#+id/q4_imageView3"
android:layout_width="0dp"
android:layout_height="189dp"
android:contentDescription="#string/red_cross"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#id/guideline6"
app:srcCompat="#mipmap/motion_time_graph" />
<TextView
android:id="#+id/q4_text"
style="#style/QuestionText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_imageView3" />
<TextView
android:id="#+id/q4_i_text"
style="#style/QuestionText"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_i"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_text" />
<EditText
android:id="#+id/q4_i_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toBottomOf="#+id/q4_text"
app:layout_constraintTop_toTopOf="#+id/q4_i_text" />
<TextView
android:id="#+id/q4_ii_text"
style="#style/QuestionText"
android:layout_width="291dp"
android:layout_height="36dp"
android:layout_marginTop="10dp"
android:text="#string/q4_ii"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_i_text" />
<EditText
android:id="#+id/q4_ii_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toTopOf="#+id/q4_ii_text" />
<TextView
android:id="#+id/q4_iii_text"
style="#style/QuestionText"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_iii"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_ii_text" />
<EditText
android:id="#+id/q4_iii_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toTopOf="#+id/q4_iii_text" />
<TextView
android:id="#+id/q4_iv_text"
style="#style/QuestionText"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_iv"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_iii_text" />
<EditText
android:id="#+id/q4_iv_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toTopOf="#+id/q4_iv_text" />
<Button
android:id="#+id/reset"
style="#style/SubmitResetButton"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/reset"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline4"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/guideline7"
app:layout_constraintVertical_bias="0.0"
android:onClick="resetAnswers"/>
<Button
android:id="#+id/submit"
style="#style/SubmitResetButton"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintStart_toStartOf="#+id/guideline4"
app:layout_constraintTop_toBottomOf="#+id/guideline7"
app:layout_constraintVertical_bias="0.0"
android:onClick="showScore"/>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="734dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
///
Button onClick and RadioGroup onClick are not the same. Please use this:
myradioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
});
I'm implementing a Camera app on Android, I'd like to have a button on it which will lead the user to the developer website, or my website.
This button is placed right of the shutter button.
I was trying to call the webview activity from this button, but it's giving me errors and I'm confused on this case, because there are plenty of examples of calling an activity inside another one, but no from a camera app.
I don't know what am I doing wrong.
Here's the piece of code in MainActivity:
public class MainActivity extends Activity /**implements OnClickListener**/ {
ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
Button webButton;
LinearLayout progressLayout;
String path = "/sdcard/KutCamera/cache/images/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
webButton = (Button) findViewById(R.id.imageView_world);
fotoButton = (ImageView) findViewById(R.id.imageView_foto);
exitButton = (Button) findViewById(R.id.button_exit);
image = (ImageView) findViewById(R.id.imageView_photo);
progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
preview = new Preview(this,
(SurfaceView) findViewById(R.id.KutCameraFragment));
FrameLayout frame = (FrameLayout) findViewById(R.id.preview);
frame.addView(preview);
preview.setKeepScreenOn(true);
fotoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
takeFocusedPicture();
} catch (Exception e) {
}
exitButton.setClickable(false);
fotoButton.setClickable(false);
webButton.setClickable(true);
progressLayout.setVisibility(View.VISIBLE);
}
});
webButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, WebActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
Everytime I run it it throws me this error:
4-04 00:33:43.929 4237-4237/com.kut.kutcamera E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kut.kutcamera/com.kut.kutcamera.MainActivity}: java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.Button
at com.kut.kutcamera.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:5283)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
The layout declaration of the world button is just Okay, I don't really think it's because of that, I guess there is something inside that camera method that doesn't allows me to properly make the call.
Can anybody shed some light on this?
Thanks in advance!
EDIT
activiy_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<SurfaceView
android:id="#+id/KutCameraFragment"
android:name="com.kut.camera.KutCameraFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<RelativeLayout
android:id="#+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alpha="1"
android:background="#android:color/black"
android:orientation="vertical"
android:padding="10dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textViewReferan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Photo"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/button_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:color/transparent"
android:text="Ok"
android:textColor="#2799CF" />
</RelativeLayout>
<LinearLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/islem_value_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading..." />
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:alpha="0.9"
android:background="#android:color/black"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView_foto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/camera"
android:contentDescription="1" />
<ImageView
android:id="#+id/imageView_photo"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="#drawable/fotocekicon"
android:contentDescription="2" />
<ImageView
android:id="#+id/imageView_world"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="#drawable/world"
android:contentDescription="2" />
</RelativeLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mark3"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</FrameLayout>
</FrameLayout>
Hi I have update your activity class, just replace with my code let me know you still face the problem.
public class MainActivity extends Activity /**implements OnClickListener**/ {
ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
ImageView webButton;
LinearLayout progressLayout;
String path = "/sdcard/KutCamera/cache/images/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
webButton = (ImageView) findViewById(R.id.imageView_world);
fotoButton = (ImageView) findViewById(R.id.imageView_foto);
exitButton = (Button) findViewById(R.id.button_exit);
image = (ImageView) findViewById(R.id.imageView_photo);
progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
preview = new Preview(this,
(SurfaceView) findViewById(R.id.KutCameraFragment));
FrameLayout frame = (FrameLayout) findViewById(R.id.preview);
frame.addView(preview);
preview.setKeepScreenOn(true);
fotoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
takeFocusedPicture();
} catch (Exception e) {
}
exitButton.setClickable(false);
fotoButton.setClickable(false);
webButton.setClickable(true);
progressLayout.setVisibility(View.VISIBLE);
}
});
webButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, WebActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
Thank you
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);
I am trying to create a spinner with key value pair in fragment. I am getting this logcat output:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ica.icadashboard/com.ica.icadashboard.HomeActivity}: java.lang.NullPointerException
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
android.app.ActivityThread.access$600(ActivityThread.java:141)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:5041)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
dalvik.system.NativeStart.main(Native Method)
05-20 08:06:36.247: E/AndroidRuntime(2746): Caused by: java.lang.NullPointerException
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
com.ica.placement.PlacementFragment.setSpinnerContent(PlacementFragment.java:44)
com.ica.placement.PlacementFragment.onCreateView(PlacementFragment.java:29)
android.app.Fragment.performCreateView(Fragment.java:1695)
android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
android.app.BackStackRecord.run(BackStackRecord.java:682)
android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
android.app.Activity.performStart(Activity.java:5113)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
05-20 08:06:36.247: E/AndroidRuntime(2746): ... 11 more
The fragment class:
public class PlacementFragment extends Fragment {
Spinner adm_spinner;
Activity activity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_placement, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
return container;
}
private void setSpinnerContent( View view )
{
adm_spinner = (Spinner) view.findViewById( R.id.adm_spinner );
final MyData items[] = new MyData[4];
for (int i = 0; i <= 3; i++) {
items[i] = new MyData("value " + i, "" + i);
}
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(activity,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adm_spinner.setAdapter(adapter);
// spinner.setAdapter( adapter );
}
class MyData {
public MyData(String spinnerText, String value) {
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public String getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
String value;
}
}
The layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Placement Analysis"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:paddingTop="5dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Spinner
android:id="#+id/tp_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
<Spinner
android:id="#+id/adm_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
</LinearLayout>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Spinner
android:id="#+id/centre_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
<Spinner
android:id="#+id/vertical_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
</LinearLayout>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="#+id/calendar_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calendar" />
<Button
android:id="#+id/process_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Process" />
</LinearLayout>
</TableRow>
</TableLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
What is the problem? Where am I going wrong? How should I populate the spinner?
You should
return view;
instead of
return container;
in your onCreateView(.....) in PlacementFragment
also change this
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(activity,
android.R.layout.simple_spinner_item, items);
to
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(getActivity(),
android.R.layout.simple_spinner_item, items);
Caused by: java.lang.NullPointerException
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
Apart form the other answer you need to change to
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(getActivity(),
android.R.layout.simple_spinner_item, items);
Activity activity; activity is not initialized.
Try this..
You have not initialize Activity activity initialize it as
activity = getActivity();
I am making an android weather app that fetches the data from a third party API and present 5 days of weather data to the user. Whenever I try to run my app it crashes. Any help would be appreciated.
Main Activity-
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private TextView mylocation;
private TextView Entry1, Entry2, Entry3, Entry4, Entry5;
private JSONObject jobject1, jobject2, jarray, tempjobject;
private JSONArray temparray;
private String provider, string, city;
private String[] maximum = new String[5];
private String[] minimum = new String[5];
private String[] conditions = new String[5];
private String[] pictureLink = new String[5];
private Bitmap[] imageCases = new Bitmap[5];
private ImageView iv1, iv2, iv3, iv4, iv5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
mylocation = (TextView) findViewById(R.id.TextView06);
iv1 = (ImageView) findViewById(R.id.iv1);
iv2 = (ImageView) findViewById(R.id.iv2);
iv3 = (ImageView) findViewById(R.id.iv3);
iv4 = (ImageView) findViewById(R.id.iv4);
iv5 = (ImageView) findViewById(R.id.iv5);
Entry1 = (TextView) findViewById(R.id.day1);
Entry2 = (TextView) findViewById(R.id.day2);
Entry3 = (TextView) findViewById(R.id.day3);
Entry4 = (TextView) findViewById(R.id.day4);
Entry5 = (TextView) findViewById(R.id.day5);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
String result;
try {
result = new WeatherHttpClient().execute("http://api.wunderground.com/api/796da11422ba3dc2/forecast10day/q/"+city+".json").get();
try {
jobject1 = new JSONObject(result);
jarray = jobject1.getJSONObject("forecast");
jobject2 = jarray.getJSONObject("simpleforecast");
temparray = jobject2.getJSONArray("forecastday");
string = result;
for(int i=0;i<2;i++){
tempjobject= temparray.getJSONObject(i);
maximum[i] =tempjobject.getString("high");
minimum[i] = tempjobject.getString("low");
conditions[i] = tempjobject.getString("conditions");
}
JSONObject j1 = new JSONObject(maximum[0]);
JSONObject j2 = new JSONObject(minimum[0]);
JSONObject j3 = new JSONObject(maximum[1]);
JSONObject j4 = new JSONObject(minimum[1]);
JSONObject j5 = new JSONObject(maximum[2]);
JSONObject j6 = new JSONObject(minimum[2]);
JSONObject j7 = new JSONObject(maximum[3]);
JSONObject j8 = new JSONObject(minimum[3]);
JSONObject j9 = new JSONObject(maximum[4]);
JSONObject j10 = new JSONObject(minimum[4]);
Entry1.setText("Maximum" + j1.getString("fahrenheit")+"°F" + "Minimum" + j2.getString("fahrenheit")+"°F "+ conditions[0]);
Entry2.setText("Maximum" + j3.getString("fahrenheit")+"°F" + "Minimum" + j4.getString("fahrenheit")+"°F "+ conditions[1]);
Entry3.setText("Maximum" + j5.getString("fahrenheit")+"°F" + "Minimum" + j6.getString("fahrenheit")+"°F "+ conditions[2]);
Entry4.setText("Maximum" + j7.getString("fahrenheit")+"°F" + "Minimum" + j8.getString("fahrenheit")+"°F "+ conditions[3]);
Entry5.setText("Maximum" + j9.getString("fahrenheit")+"°F" + "Minimum" + j10.getString("fahrenheit")+"°F "+ conditions[4]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<5;i++){
imageCases[i] = new Image().execute(pictureLink[i]).get();
}
iv1.setImageBitmap(imageCases[0]);
iv2.setImageBitmap(imageCases[1]);
iv3.setImageBitmap(imageCases[2]);
iv4.setImageBitmap(imageCases[3]);
iv5.setImageBitmap(imageCases[5]);
Toast.makeText(getBaseContext(), string, Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Geocoder geoCoder1 = new Geocoder(getBaseContext(), Locale.getDefault());
try {
String add = "";
List<Address> addresses;
List<Address> fromLocation;
fromLocation = (List<Address>) geoCoder1.getFromLocation(lat,lng, 1);
addresses = fromLocation;
if (addresses.size() > 0)
{
for (int i=0; i<((android.location.Address) addresses.get(0)).getMaxAddressLineIndex();i++)
add += ((android.location.Address) addresses.get(0)).getAddressLine(i) + "\n";
}
mylocation.setText(String.valueOf(add));
Bundle extras = getIntent().getExtras();
if (extras != null) {
city = extras.getString("ZipCode");
}
else{
city = ((android.location.Address) addresses.get(0)).getPostalCode();
}
Toast.makeText(getBaseContext(), city, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_settings:
Intent aboutIntent = new Intent(MainActivity.this, Options.class);
startActivity(aboutIntent);
return true;
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
XML-
<?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:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:orientation="vertical" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="#string/Lati"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="#string/Longi"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="#string/Locati"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/TextView06"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d1"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv1"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="xxxxxxx"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d2"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv2"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d3"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv3"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d4"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv4"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:paddingTop="15dip"
android:text="#string/d5"
android:textSize="20sp" >
</TextView>
<ImageView
android:id="#+id/iv5"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="Image for climate"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="#+id/day5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyyyyyyyy"
android:textSize="20sp" >
</TextView>
</LinearLayout>
</ScrollView>
LogCat Output
10-17 22:26:33.834: D/ActivityThread(29954): setTargetHeapUtilization:0.25
10-17 22:26:33.834: D/ActivityThread(29954): setTargetHeapIdealFree:8388608
10-17 22:26:33.834: D/ActivityThread(29954): setTargetHeapConcurrentStart:2097152
10-17 22:26:34.014: I/System.out(29954): Provider network has been selected.
10-17 22:26:34.705: W/dalvikvm(29954): threadid=1: thread exiting with uncaught exception (group=0x41e90438)
10-17 22:26:34.705: E/AndroidRuntime(29954): FATAL EXCEPTION: main
10-17 22:26:34.705: E/AndroidRuntime(29954): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.checkweather/com.example.checkweather.MainActivity}: java.lang.NullPointerException
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.access$700(ActivityThread.java:143)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.os.Handler.dispatchMessage(Handler.java:99)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.os.Looper.loop(Looper.java:137)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.main(ActivityThread.java:4950)
10-17 22:26:34.705: E/AndroidRuntime(29954): at java.lang.reflect.Method.invokeNative(Native Method)
10-17 22:26:34.705: E/AndroidRuntime(29954): at java.lang.reflect.Method.invoke(Method.java:511)
10-17 22:26:34.705: E/AndroidRuntime(29954): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
10-17 22:26:34.705: E/AndroidRuntime(29954): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
10-17 22:26:34.705: E/AndroidRuntime(29954): at dalvik.system.NativeStart.main(Native Method)
10-17 22:26:34.705: E/AndroidRuntime(29954): Caused by: java.lang.NullPointerException
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONObject.<init>(JSONObject.java:154)
10-17 22:26:34.705: E/AndroidRuntime(29954): at org.json.JSONObject.<init>(JSONObject.java:171)
10-17 22:26:34.705: E/AndroidRuntime(29954): at com.example.checkweather.MainActivity.onCreate(MainActivity.java:103)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.Activity.performCreate(Activity.java:5179)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
10-17 22:26:34.705: E/AndroidRuntime(29954): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
10-17 22:26:34.705: E/AndroidRuntime(29954): ... 11 more
You only create values for maximum[0] and maximum[1], same for minimum.
So when you call
JSONObject j4 = new JSONObject(minimum[2]);
you pass null to the JSONObject.