Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, so currently what i am attempting to create a currency convertor app by referencing what other people did such as the example here
android-studio-with-the-use-of-api-38d07e8253fc">https://medium.com/@kanchanaj/how-to-create-a-simple-currency-converter-app-in-android-studio-with-the-use-of-api-38d07e8253fc[^]

but the issue that i am currently facing now is that i am unsure of the part on the MainActivity as to where and how i should be placing the code for the MainActivity as seen in the link. Should i be placing it in the MainActivity as seen in the link above or should i be placing it inside the fragment that i have created? and if so how should it be placed inside the fragment? Here is an example of my fragment

Java
  1  package sg.edu.rp.c346.new4thappcurrencyconvertorpd;
  2  
  3  
  4  import android.os.Bundle;
  5  
  6  import androidx.fragment.app.Fragment;
  7  
  8  import android.util.Log;
  9  import android.view.LayoutInflater;
 10  import android.view.View;
 11  import android.view.ViewGroup;
 12  import android.widget.ArrayAdapter;
 13  import android.widget.Spinner;
 14  import android.widget.TextView;
 15  import android.widget.Toast;
 16  
 17  import com.squareup.okhttp.Callback;
 18  import com.squareup.okhttp.OkHttpClient;
 19  import com.squareup.okhttp.Request;
 20  import com.squareup.okhttp.Response;
 21  
 22  import org.json.JSONException;
 23  import org.json.JSONObject;
 24  
 25  import java.io.IOException;
 26  import java.text.BreakIterator;
 27  import java.util.ArrayList;
 28  import java.util.Iterator;
 29  import java.util.List;
 30  
 31  
 32  /**
 33   * A simple {@link Fragment} subclass.
 34   */
 35  public class HomeFragment extends Fragment implements View.OnClickListener{
 36      public static BreakIterator data;
 37      List<String> keysList;
 38      Spinner toCurrency;
 39      TextView textView;
 40  
 41  
 42      public HomeFragment() {
 43          // Required empty public constructor
 44      }
 45  
 46  
 47      @Override
 48      public View onCreateView(LayoutInflater inflater, ViewGroup container,
 49                               Bundle savedInstanceState) {
 50          // Inflate the layout for this fragment
 51          return inflater.inflate(R.layout.fragment_home, container, false);
 52      }
 53  
 54      @Override
 55      public void onClick(View v) {
 56          btnConvert.setOnClickListener(new View.OnClickListener() {
 57              @Override
 58              public void onClick(View v) {
 59                  if(!edtEuroValue.getText().toString().isEmpty())
 60                  {
 61                      String toCurr = toCurrency.getSelectedItem().toString();
 62                      double euroVlaue = Double.valueOf(edtEuroValue.getText().toString());
 63  
 64                      Toast.makeText(MainActivity.this, "Please Wait..", Toast.LENGTH_SHORT).show();
 65                      try {
 66                          convertCurrency(toCurr, euroVlaue);
 67                      } catch (IOException e) {
 68                          e.printStackTrace();
 69                          Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
 70                      }
 71                  }
 72                  else
 73                  {
 74                      Toast.makeText(MainActivity.this, "Please Enter a Value to Convert..", Toast.LENGTH_SHORT).show();
 75                  }
 76  
 77              }
 78          });
 79  
 80      }
 81  
 82      public void loadConvTypes() throws IOException {
 83  
 84          String url = "https://api.exchangeratesapi.io/latest";
 85  
 86          OkHttpClient client = new OkHttpClient();
 87  
 88          Request request = new Request.Builder()
 89                  .url(url)
 90                  .header("Content-Type", "application/json")
 91                  .build();
 92  
 93  
 94  
 95          client.newCall(request).enqueue(new Callback() {
 96              @Override
 97              public void onFailure(Request request, IOException e) {
 98                  String mMessage = e.getMessage().toString();
 99                  Log.w("failure Response", mMessage);
100                  Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
101              }
102  
103              @Override
104              public void onResponse(Response response) throws IOException {
105                  final String mMessage = response.body().string();
106  
107  
108                  MainActivity.this.runOnUiThread(new Runnable() {
109                      @Override
110                      public void run() {
111                          //Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
112                          try {
113                              JSONObject obj = new JSONObject(mMessage);
114                              JSONObject  b = obj.getJSONObject("rates");
115  
116                              Iterator keysToCopyIterator = b.keys();
117                              keysList = new ArrayList<String>();
118  
119                              while(keysToCopyIterator.hasNext()) {
120  
121                                  String key = (String) keysToCopyIterator.next();
122  
123                                  keysList.add(key);
124  
125                              }
126  
127  
128                              ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, keysList );
129                              toCurrency.setAdapter(spinnerArrayAdapter);
130  
131  
132  
133  
134  
135                          } catch (JSONException e) {
136                              e.printStackTrace();
137                          }
138  
139                      }
140                  });
141              }
142  
143  
144  
145  
146          });
147      }
148  
149      public void convertCurrency(final String toCurr, final double euroVlaue) throws IOException {
150  
151          String url = "https://api.exchangeratesapi.io/latest";
152  
153          OkHttpClient client = new OkHttpClient();
154  
155          Request request = new Request.Builder()
156                  .url(url)
157                  .header("Content-Type", "application/json")
158                  .build();
159  
160  
161  
162          client.newCall(request).enqueue(new Callback() {
163              @Override
164              public void onFailure(Request request, IOException e) {
165                  String mMessage = e.getMessage().toString();
166                  Log.w("failure Response", mMessage);
167                  Toast.makeText(HomeFragment.this, mMessage, Toast.LENGTH_SHORT).show();
168              }
169  
170              @Override
171              public void onResponse(Response response) throws IOException {
172                  final String mMessage = response.body().string();
173                  HomeFragment.this.runOnUiThread(new Runnable() {
174                      @Override
175                      public void run() {
176                          //Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
177                          try {
178                              JSONObject obj = new JSONObject(mMessage);
179                              JSONObject  b = obj.getJSONObject("rates");
180  
181                              String val = b.getString(toCurr);
182  
183                              double output = euroVlaue*Double.valueOf(val);
184  
185  
186                              textView.setText(String.valueOf(output));
187  
188                          } catch (JSONException e) {
189                              e.printStackTrace();
190                          }
191  
192                      }
193                  });
194              }
195  
196  
197  
198  
199  
200          });
201      }
202      }


What I have tried:

so what i have currently tried is to follow the instructions as seen in the link above accordingly and placed it in the MainActivity by itself. but however i then came to this issue
Process: sg.edu.rp.c346.new4thappcurrencyconvertorpd, PID: 8656
   java.lang.RuntimeException: Unable to start activity ComponentInfo{sg.edu.rp.c346.new4thappcurrencyconvertorpd/sg.edu.rp.c346.new4thappcurrencyconvertorpd.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:193)
       at android.app.ActivityThread.main(ActivityThread.java:6669)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
       at sg.edu.rp.c346.new4thappcurrencyconvertorpd.MainActivity.onCreate(MainActivity.java:66)
       at android.app.Activity.performCreate(Activity.java:7136)
       at android.app.Activity.performCreate(Activity.java:7127)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
       at android.os.Handler.dispatchMessage(Handler.java:106) 
       at android.os.Looper.loop(Looper.java:193) 
       at android.app.ActivityThread.main(ActivityThread.java:6669) 
       at java.lang.reflect.Method.invoke(Native Method) 
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858


I'm not very familiar with fragments and am currently still learning android here, so my sincere apologies if my questions seem stupid.
Posted
Updated 4-Apr-20 4:32am
v2
Comments
David Crow 6-Apr-20 10:11am    
If you are using Android Studio, you should be getting a compile error at/around line 56, as btnConvert has neither been declared nor initialized.

In the onCreate() method, you'll likely need something like:
btnConvert = findViewById(R.id.button);
RookieStudent 7-Apr-20 2:49am    
but i had it written already though in my MainActivity, here it is:

package sg.edu.rp.c346.new4thappcurrencyconvertorpd;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends AppCompatActivity {

public static BreakIterator data;
List<string> keysList;
Spinner toCurrency;
TextView textView;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(navListener);
NavigationUI.setupWithNavController(bottomNav, navController);

getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new HomeFragment());

toCurrency = (Spinner)findViewById(R.id.planets_spinner);
final EditText edtEuroValue = (EditText)findViewById(R.id.editText4);
final Button btnConvert = (Button)findViewById(R.id.button);
textView =(TextView) findViewById(R.id.textView7);
try {
loadConvTypes();
} catch (IOException e) {
e.printStackTrace();
}

btnConvert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!edtEuroValue.getText().toString().isEmpty())
{
String toCurr = toCurrency.getSelectedItem().toString();
double euroVlaue = Double.valueOf(edtEuroValue.getText().toString());

Toast.makeText(MainActivity.this, "Please Wait..", Toast.LENGTH_SHORT).show();
try {
convertCurrency(toCurr, euroVlaue);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "Please Enter a Value to Convert..", Toast.LENGTH_SHORT).show();
}

}
});

}

public void loadConvTypes() throws IOException {

String url = "https://api.exchangeratesapi.io/latest";

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.build();



client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
String mMessage = e.getMessage().toString();
Log.w("failure Response",
David Crow 7-Apr-20 8:09am    
Your class HomeFragment has no such declaration for btnConvert. MainActivity does, however.

BTW, there's no need to show the entire class. Just show the relevant parts.
RookieStudent 8-Apr-20 0:38am    
ah sorry my bad. But I would like to ask though as im not very familiar with the use of fragments, for my HomeFragment is the code that should be used is as same as the one applied to the MainActivity though? My apologise if my question seems poorly structured.
David Crow 8-Apr-20 8:09am    
"for my HomeFragment is the code that should be used is as same as the one applied to the MainActivity though?"

I do not understand this question.

1 solution

Java
55      public void onClick(View v) {
56          btnConvert.setOnClickListener(new View.OnClickListener() {
57              @Override

You have not declared btnConvert anywhere that I can see, or connected it to the visual component.
 
Share this answer
 
Comments
RookieStudent 4-Apr-20 11:35am    
sorry! but here it is


<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
="" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".HomeFragment">


<imageview
android:id="@+id/cashimage"
="" android:layout_width="100dp" android:layout_height="100dp" android:layout_alignend="@+id/button" android:layout_alignright="@+id/button" android:layout_alignparenttop="true" android:layout_gravity="center_horizontal" android:layout_margintop="20dp" android:layout_marginend="-45dp" android:layout_marginright="-45dp" android:src="@drawable/currency">

<textview
android:id="@+id/textView5"
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignstart="@+id/textView4" android:layout_alignparenttop="true" android:layout_marginstart="0dp" android:layout_margintop="231dp" android:text="Curency">

<spinner
android:id="@+id/planets_spinner"
="" android:layout_width="220dp" android:layout_height="wrap_content" android:layout_aligntop="@+id/textView5" android:layout_marginleft="70dp" android:layout_margintop="1dp">

<textview
android:id="@+id/textView4"
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentstart="true" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:layout_marginstart="41dp" android:layout_marginleft="41dp" android:layout_margintop="164dp" android:text="Amount">

<edittext
android:id="@+id/editText4"
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignbottom="@+id/textView4" android:layout_centerhorizontal="true" android:layout_marginbottom="-16dp" android:ems="10" android:inputtype="number">


<button
android:id="@+id/button"
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentstart="true" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:layout_marginstart="125dp" android:layout_marginleft="125dp" android:layout_margintop="297dp" android:text="Convert">

<textview
android:id="@+id/textView6"
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentstart="true" android:layout_alignparentleft="true" android:layout_alignparentbottom="true" android:layout_marginstart="51dp" android:layout_marginleft="51dp" android:layout_marginbottom="113dp" android:text="Value">

<textview
android:id="@+id/textView7"
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_aligntop="@+id/textView6" android:layout_marginstart="44dp" android:layout_margintop="0dp" android:layout_toendof="@+id/textView5" android:text="TextView">
Richard MacCutchan 4-Apr-20 11:46am    
Very interesting but where is btnConvert?
Richard MacCutchan 4-Apr-20 11:49am    
Looking at the original code it appears that you have missed out the part where the button is initialised. I suggest you go back to the original code and copy it more carefully.
RookieStudent 5-Apr-20 4:18am    
hi, but after re-attempting it though i still encounter the same error. Does it have anything to do due to the fact that i did not place the set of codes as seen above into the java class where i have created the layout for ? sorry if my question seems poorly phrased here
Richard MacCutchan 5-Apr-20 4:29am    
You must connect the btnConvert reference to the actual object in the view at runtime. If you do not understand the basics of Android processes there are plenty of tutorials and samples here on CodeProject, and at dedicated Android developer websites.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900