HTTP Request Android - Attempt to invoke virtual method - java
So I have a problem. I have been trying to get an http request to work for quite a while now, and I have made a new thread so that the request never runs on the main thread. I have successfully made it so that the HTTP Request occurs and in the request thread I have made it so it logs the data that it has grabbed from the http request. Now if I ever want to use this jsonObject outside the method it gives me errors. Help?
LogCat:
02-23 22:48:08.612 4239-4239/com.tamrefrank.www.listviewandroidstudio E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tamrefrank.www.listviewandroidstudio, PID: 4239
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tamrefrank.www.listviewandroidstudio/com.tamrefrank.www.listviewandroidstudio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONArray.toString()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONArray.toString()' on a null object reference
at com.tamrefrank.www.listviewandroidstudio.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-23 22:48:09.332 4239-4254/com.tamrefrank.www.listviewandroidstudio I/log_tag﹕ [{"Name":"Cabinet","Location":"In Storage","Latitude":"40.83990100","Longitude":"14.25185000","pk":19587,"image_id":"2006AJ6728"},{"Name":"Panel","Location":"Medieval and Renaissance, room 8, case WS EXP","Latitude":"48.87287900","Longitude":"4.63710000","pk":11371,"image_id":"2006AP3163"},{"Name":"Wallpaper","Location":"British Galleries, room 122f, case 1","Latitude":"53.47962200","Longitude":"-2.24881000","pk":19492,"image_id":"2006AU6265"},{"Name":"Portrait miniature","Location":"British Galleries, room 58c, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":9491,"image_id":"2006AH0271"},{"Name":"Caricature","Location":"In Storage","Latitude":"53.02513900","Longitude":"-2.18676000","pk":29979,"image_id":"2006AE9142"},{"Name":"Card game","Location":"In Storage","Latitude":"52.88328900","Longitude":"-1.97685000","pk":26483,"image_id":"2006AU5916"},{"Name":"Tile","Location":"Islamic Middle East, room 42, case WW9","Latitude":"39.76586200","Longitude":"64.42234000","pk":30220,"image_id":"2006AY5617"},{"Name":"Sculpture","Location":"Sculpture, room 22, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":36026,"image_id":"2006AM7780"},{"Name":"Oil painting","Location":"Prints & Drawings Study Room, room 315, case 24, shelf R","Latitude":"52.88328900","Longitude":"-1.97685000","pk":6905,"image_id":"2006AU6480"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10895,"image_id":"2006AU8783"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10902,"image_id":"2006AU9234"}]
02-23 22:48:09.332 4239-4254/com.tamrefrank.www.listviewandroidstudio I/log_tag﹕ [{"Name":"Cabinet","Location":"In Storage","Latitude":"40.83990100","Longitude":"14.25185000","pk":19587,"image_id":"2006AJ6728"},{"Name":"Panel","Location":"Medieval and Renaissance, room 8, case WS EXP","Latitude":"48.87287900","Longitude":"4.63710000","pk":11371,"image_id":"2006AP3163"},{"Name":"Wallpaper","Location":"British Galleries, room 122f, case 1","Latitude":"53.47962200","Longitude":"-2.24881000","pk":19492,"image_id":"2006AU6265"},{"Name":"Portrait miniature","Location":"British Galleries, room 58c, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":9491,"image_id":"2006AH0271"},{"Name":"Caricature","Location":"In Storage","Latitude":"53.02513900","Longitude":"-2.18676000","pk":29979,"image_id":"2006AE9142"},{"Name":"Card game","Location":"In Storage","Latitude":"52.88328900","Longitude":"-1.97685000","pk":26483,"image_id":"2006AU5916"},{"Name":"Tile","Location":"Islamic Middle East, room 42, case WW9","Latitude":"39.76586200","Longitude":"64.42234000","pk":30220,"image_id":"2006AY5617"},{"Name":"Sculpture","Location":"Sculpture, room 22, case 2","Latitude":"52.88328900","Longitude":"-1.97685000","pk":36026,"image_id":"2006AM7780"},{"Name":"Oil painting","Location":"Prints & Drawings Study Room, room 315, case 24, shelf R","Latitude":"52.88328900","Longitude":"-1.97685000","pk":6905,"image_id":"2006AU6480"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10895,"image_id":"2006AU8783"},{"Name":"Snuff bottle","Location":"In Storage","Latitude":"36.89445100","Longitude":"104.16564900","pk":10902,"image_id":"2006AU9234"}]
02-23 22:48:32.712 4239-4239/com.tamrefrank.www.listviewandroidstudio I/Process﹕ Sending signal. PID: 4239 SIG: 9
Code:
package com.tamrefrank.www.listviewandroidstudio;
//All the imports happen when you auto complete. Often you may have erros when you copy paste things directly because libraries may not get imported
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends ActionBarActivity {
private String [] drinks;
JSONArray jsonObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the content view to activity_main.xml
setContentView(R.layout.activity_main);
JSONArray object = new JSONArray();
object = getData();
Log.i("log_tag", jsonObject.toString());
// System.out.print("success: " + object.toString());
drinks = new String[3];
drinks[0] = "hi";
drinks[1] = "5";
drinks[2] = "3";
/**
* Lists require adapters-Adapters are the place that we store the various data items we want
to appear in the Lists. This will be handled in an adapter.
*/
ArrayAdapter<String> adapter;
//We will create the array adapter and reference it to our individual List item from the ListView and then to the array we just created- Drinks.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,drinks);
//We finally will connect the adapter to the List View
ListView drinkLists = (ListView) findViewById(R.id.listView);
//Set the drinks array to the adapter below
drinkLists.setAdapter(adapter);
}
public JSONArray getData(){
new Thread(new Runnable() {
public void run() {
HttpGet httpGet = new HttpGet("https://stampwatch.herokuapp.com/");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
System.out.println(e);
}
try {
jsonObject = new JSONArray(stringBuilder.toString());
Log.i("log_tag", jsonObject.toString());
;
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("log_tag", jsonObject.toString());
}
}).start();
return jsonObject;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here:
Log.i("log_tag", jsonObject.toString());
NPE because jsonObject is null and trying to call toString() method for JSONObject using null object.
But why is the object null if I have made a request with that object?
Because jsonObject object is initialized inside getData(); method in which a Thread is used for getting data from api. means :
Log.i("log_tag", jsonObject.toString());
line executing just after starting Thread instead of wait until thread is finish.
Related
AndroidStudio- Fatal error: IndexOutOfBoundsException: Invalid index 0, size is 0
I was able to run my app successfully through the emulator. but suddenly a bunch of errors appeared so now I am not able to launch it. There is a Fatal error. Here is LogCat output: 08-26 12:14:27.937 2112-2112/com.joudi.myapplication D/AndroidRuntime﹕ Shutting down VM 08-26 12:14:27.938 2112-2112/com.joudi.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.joudi.myapplication, PID: 2112 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.joudi.myapplication/com.joudi.myapplication.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.joudi.myapplication.MainActivity.onCreate(MainActivity.java:29) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) I do not know ow to fix the "IndexOutOfBoundsException: Invalid index 0, size is 0" error. Here is my MainActicity.java file code: import android.graphics.Canvas; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import com.joudi.myapplication.data.NoteItem; import com.joudi.myapplication.data.NotesDataSource; import java.util.List; public class MainActivity extends AppCompatActivity { private NotesDataSource datasource; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); datasource = new NotesDataSource(this); List<NoteItem> notes= datasource.findAll(); NoteItem note = notes.get(0); note.setText("Updated!"); datasource.update(note); notes= datasource.findAll(); note= notes.get(0); Log.i("NOTES", note.getKey()); } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Looks looks datasource.findAll();returns an empty list. notes.get(0); throws the exception. You should check if the size of the list is greater then 0. if (notes.size() >0){ NoteItem note = notes.get(0); note.setText("Updated!"); datasource.update(note); }
You need to check the size of notes before trying to access its element: List<NoteItem> notes= datasource.findAll(); // Check the value of notes to avoid IndexOutOfBoundsException if (null!=notes || notes.size()>0){ note = notes.get(0); }
Header not getting set properly in android-Retrofit
I'm building an app for sending access-token to the server using Retrofit in android. I don't get any error what I think should set the header correctly is not working so. The header that I want: "Authorization: Bearer facebook <user_access_token>" is the token that I get. Not written here for security purposes. I am using android Retrofit for the purpose with the files as follows: MainActivity.java package com.example.apurva.myapplication; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.os.StrictMode; public class MainActivity extends ActionBarActivity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); UserService userService; String token = "Bearer facebook <user_access_token>"; userService = ServiceGenerator.createService(UserService.class, UserService.BASE_URL, token); User user = userService.me(); } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } UserService.java package com.example.apurva.myapplication; import com.squareup.okhttp.OkHttpClient; import retrofit.Callback; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.POST; /** * Created by apurva on 4/8/15. */ public interface UserService { public static final String BASE_URL = "http://10.0.2.2:8000/auth"; #POST("/convert-token") User me(); } ServiceGenerator.java package com.example.apurva.myapplication; import com.squareup.okhttp.OkHttpClient; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; /** * Created by apurva on 4/8/15. */ public class ServiceGenerator { private ServiceGenerator() { } public static <S> S createService(Class<S> serviceClass, String baseUrl, final String token) { RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(baseUrl) .setClient(new OkClient(new OkHttpClient())); if (token != null) { builder.setRequestInterceptor(new RequestInterceptor() { #Override public void intercept(RequestFacade request) { request.addHeader("Accept", "application/json"); request.addHeader("Authorization", token); } }); } RestAdapter adapter = builder.build(); return adapter.create(serviceClass); } } I would like to mention that there are no errors. I have already set network activity in the main thread by using StrictMode so that is not an issue as well just it does not give the desired result as the user in not getting added in the backend. I would also like to tel you that I've already checked my back end with cURL and it works fine so there is no issue there as well. I get runtime error: Process: com.example.apurva.myapplication, PID: 7140 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apurva.myapplication/com.example.apurva.myapplication.MainActivity}: retrofit.RetrofitError: 405 METHOD NOT ALLOWED at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: retrofit.RetrofitError: 405 METHOD NOT ALLOWED at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:388) at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240) at $Proxy0.me(Native Method) at com.example.apurva.myapplication.MainActivity.onCreate(MainActivity.java:24) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method)
Your code is ok. You should add logging to your Retrofit. // Simple add .setLogLevel(RestAdapter.LogLevel.FULL) RestAdapter.Builder builder = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint(baseUrl) .setClient(new OkClient(new OkHttpClient())); I'm sure after this you will see in console: ---> HTTP POST http://10.0.2.2:8000/auth/convert-token Accept: application/json Authorization: Bearer facebook <user_access_token> ---> END HTTP (no body) That means your header is set correctly. "HTTP 405 METHOD NOT ALLOWED" may say that POST method is not expected for this resource. And maybe GET request will help you: #GET("/convert-token") User me();
Hi Please Refer githublink and it will give some Idea,let me explain basic functionality here, Create a Interface: public interface MyApiEndPointInterface { /* #GET("contacts/") Call<UserPojo> getHiveDetails();*/ #FormUrlEncoded #POST("authorize/") Call<SmsLogin> getUser(#Field("username") String username, #Field("password") String password); //GetProfile Details #GET("getprofile") Call<SmsProfilePojo> getProfileDetails(#Header("Authorizations") String myTokenValue); } UserProfilePreview.java is An Activity,Please LookUp this Class in repo,It give basic Idea. private void getApiCAll() { OkHttpClient okClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { #Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Accept","Application/JSON").build(); return chain.proceed(request); } }).build(); retrofitRef = new Retrofit.Builder() .baseUrl(BASE_URL) .client(okClient) .addConverterFactory(GsonConverterFactory.create()) .build(); final MyApiEndPointInterface service = retrofitRef.create(MyApiEndPointInterface.class); String myTokenStr = "Bearer "+mToken; Call<SmsProfilePojo> call = service.getProfileDetails(myTokenStr); call.enqueue(new Callback<SmsProfilePojo>() { #Override public void onResponse(Call<SmsProfilePojo> call, retrofit2.Response<SmsProfilePojo> response) { Log.d(TAG,"OnResponse: "+ response.code()); if(response.isSuccessful()){ SmsProfilePojo result = response.body(); mToken = result.getToken(); txtVw_Token.setText(mToken); }else{ Toast.makeText(getApplicationContext(),"Fail in Response",Toast.LENGTH_SHORT).show(); } } #Override public void onFailure(Call<SmsProfilePojo> call, Throwable t) { Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_SHORT).show(); } }); }
Trying to save JSON string into a class to parce between activities (NPE)
I am trying to save my JSON string into a class so that I can pass around that object between activities and not lose any data when pressing the back button. However as I try to set the string into the object I receive a NullPointerException. Here is the code for my java file where the exception is occurring, the class java file, and the error. I am using GSON to serialize and deserialize. Any suggestions as to why this is happening? NewLocation.java package com.customledsupply.ledaudit; import android.content.Intent; import android.content.SharedPreferences; import android.os.Parcelable; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import com.google.gson.Gson; public class NewLocation extends ActionBarActivity { public EditText editCoName; public EditText editCoAddress; public EditText editCoContact; public EditText editSqFt; public EditText editTaxed; public EditText editConcerns; public JSON_String json; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_location); findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { SaveInfo(); Intent i = new Intent(NewLocation.this, RoomList.class); i.putExtra("json", (Parcelable) json); startActivity(i); } }); editCoName = (EditText) findViewById(R.id.CoName); editCoAddress = (EditText) findViewById(R.id.CoAddress); editCoContact = (EditText) findViewById(R.id.CoContact); editSqFt = (EditText) findViewById(R.id.SqFt); editTaxed = (EditText) findViewById(R.id.Taxed); editConcerns = (EditText) findViewById(R.id.Concerns); SaveInfo(); } #Override protected void onResume() { super.onResume(); LoadInfo(); } #Override protected void onDestroy() { super.onDestroy(); SaveInfo(); } public void SaveInfo() { Gson gson = new Gson(); CompanyInfo companyInfo = new CompanyInfo(); companyInfo.setName(editCoName.getText().toString()); companyInfo.setAddress(editCoAddress.getText().toString()); companyInfo.setContact(editCoContact.getText().toString()); companyInfo.setTaxed(editTaxed.getText().toString()); companyInfo.setSqFt(editSqFt.getText().toString()); companyInfo.setConcerns(editConcerns.getText().toString()); json.setJson(gson.toJson(companyInfo)); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("json", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("json", json.getJson()); editor.apply(); } public void LoadInfo() { SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("json", MODE_PRIVATE); json.setJson(sharedPreferences.getString("json", null)); Gson gson = new Gson(); CompanyInfo companyInfo = gson.fromJson(json.getJson(), CompanyInfo.class); if (companyInfo != null) { editCoName.setText(companyInfo.getName()); editCoAddress.setText(companyInfo.getAddress()); editCoContact.setText(companyInfo.getContact()); editTaxed.setText(companyInfo.getTaxed()); editSqFt.setText(companyInfo.getSqFt()); editConcerns.setText(companyInfo.getConcerns()); } } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_new_location, menu); return true; } #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch(item.getItemId()) { case R.id.home: startActivity(new Intent(getApplicationContext(), MainPage.class)); break; } return super.onOptionsItemSelected(item); } } JSON_String.java package com.customledsupply.ledaudit; public class JSON_String { private String json; public void setJson(String json) { this.json = json; } public String getJson() { return json; } } NPE error 08-03 08:46:52.081 24423-24423/com.customledsupply.ledaudit E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.customledsupply.ledaudit, PID: 24423 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.customledsupply.ledaudit/com.customledsupply.ledaudit.NewLocation}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2248) at android.app.ActivityThread.access$800(ActivityThread.java:138) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5061) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:780) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.customledsupply.ledaudit.NewLocation.SaveInfo(NewLocation.java:78) at com.customledsupply.ledaudit.NewLocation.onCreate(NewLocation.java:52) at android.app.Activity.performCreate(Activity.java:5237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2248) at android.app.ActivityThread.access$800(ActivityThread.java:138) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5061) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:780) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596) at dalvik.system.NativeStart.main(Native Method)
You're trying to cast your json to Parcelable: i.putExtra("json", (Parcelable) json); Just pass as a string and in your RoomList.class get from bundle. Cast it to your class with gson and use it.
Your json is null, hence the error. To onCreate add json = new JSON_String(); If you want to keep passing the object between activites, and not lose it when back button is pressed, you should use startActivityForResults(). This will require you to implement a couple of methods that take care of passing objects between activities. This is a good tutorial.
The problem is You didn't initialize your JSON_String class. You need to initialize the JSON_String like public JSON_String json = new JSON_String();
Have you tried to initlize the json string?
Android MediaRecorder NullPointerException
Im just starting out with Java Development and i am fiddling around with the Android Media recorder. However I am getting a NullPointerException which I click the record button using the following source code: import android.support.v7.app.ActionBarActivity; import android.os.Bundle; //import android.net.Uri; import android.view.Menu; import android.view.MenuItem; import android.os.Environment; import android.view.View; import java.io.File; import java.io.IOException; import android.media.MediaPlayer; import android.media.MediaRecorder; import java.lang.String; public class MainActivity extends ActionBarActivity { String outputFile = "test.3gp"; private MediaRecorder myAudioRecorder; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MediaRecorder myAudioRecorder = new MediaRecorder(); myAudioRecorder = new MediaRecorder(); // Uri target = Uri.parse(outputFile.getAbsolutePath()); myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); myAudioRecorder.setOutputFile(outputFile); } public void Start_Record(View v) { try { myAudioRecorder.prepare(); myAudioRecorder.start(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } myAudioRecorder.stop(); myAudioRecorder.release(); } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } I realise that this probably due to the fill pointer being set to NULL, however I am struggling to see how to initialize the file reference for this to vanish. I am getting th exception on mediaRecorderPrepare() Here is the Exception thrown: 03-09 22:53:56.548 31836-31836/uk.co.spectralgear.spectralboost E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity at android.view.View$1.onClick(View.java:4007) at android.view.View.performClick(View.java:4756) at android.view.View$PerformClick.run(View.java:19749) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at android.view.View$1.onClick(View.java:4002) at android.view.View.performClick(View.java:4756) at android.view.View$PerformClick.run(View.java:19749) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference at uk.co..MainActivity.Start_Record(MainActivity.java:38) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at android.view.View$1.onClick(View.java:4002) at android.view.View.performClick(View.java:4756) at android.view.View$PerformClick.run(View.java:19749) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Any help would be greatly appreciated:)
PROBLEM: Your class variable "myAudioRecord" is null when "Start_Record()" tries to use it: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void Android.media.MediaRecorder.prepare()' on a null object reference SOLUTION: Delete this line from your "onCreate()" method: public class MainActivity extends ActionBarActivity { String outputFile = "test.3gp"; private MediaRecorder myAudioRecorder; // Your class variable: OK... #Override protected void onCreate(Bundle savedInstanceState) { ... // MediaRecorder myAudioRecorder = new MediaRecorder(); // DELETE THIS LINE!!! myAudioRecorder = new MediaRecorder(); // OK... ... The declaration of "myAudioRecorder" inside onCreate() HIDES the outer declaration. So the outer (class-level) "myAudioRecorder" never gets initialized ... and your program dies with an NPE when "Start_Record()" tries to access it. PS: Please consider changing the method name to "start_Record()". Or better, "startRecord()". This is more consistent with Java naming conventions.
I think you are using stop() function while it was already stopped. Check your code and logic.
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
Guys I am getting an error and I am not sure how to solve it please help me. Here is my code: package com.appschool.www.projectphase1516; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import com.appschool.www.projectphase1516.R; import org.w3c.dom.Text; public class AccountlistActivity extends Activity implements View.OnClickListener { LinearLayout horiz; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_accountlist); horiz = (LinearLayout) findViewById(R.id.linearlayouthere); Accountlistcreator(); setContentView(horiz); } public void Accountlistcreator(){ SharedPreferences sp = getSharedPreferences("details",1); int numofaccounts = sp.getInt("numofaccouns",0); horiz.removeAllViews(); for(int i=0;i<=numofaccounts;i++) { TextView titleaccount = new TextView(this); titleaccount.setText(sp.getString("accountTitle" + i, "")); titleaccount.setTextSize(20); horiz.addView(titleaccount); Button seeaccount = new Button(this); seeaccount.setText("See Details"); seeaccount.setId(i); seeaccount.setLayoutParams(new FrameLayout.LayoutParams(200,100)); seeaccount.setOnClickListener(this); horiz.addView(seeaccount); } } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.accountlist, menu); return true; } #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } #Override public void onClick(View view) { SharedPreferences sp = getSharedPreferences("details",1); int num = sp.getInt("numofaccouns",0); for(int x=0;x<=num;x++){ if(view.getId()==x){ Intent myaccount = new Intent(AccountlistActivity.this,MyaccountActivity.class); myaccount.putExtra("numbtn",x); startActivity(myaccount); } } } } And here is the error I am getting: Process: com.appschool.www.projectphase1516, PID: 2751 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appschool.www.projectphase1516/com.appschool.www.projectphase1516.AccountlistActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.view.ViewGroup.addViewInner(ViewGroup.java:3562) at android.view.ViewGroup.addView(ViewGroup.java:3415) at android.view.ViewGroup.addView(ViewGroup.java:3391) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:309) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:299) at android.app.Activity.setContentView(Activity.java:1949) at com.appschool.www.projectphase1516.AccountlistActivity.onCreate(AccountlistActivity.java:29) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Please help me out guys! The code should create a specific number of buttons and textviews. I am trying to remove and recreate all of them everytime I am going to that activity and am not sure why I keep getting an error :[ EDIT: thanks it now runs but there is another problem it doesnt create more than 1 textview and a button and i am not sure why (i am pretty new to java development,so i dont know complex features like the comment above me ) i am just doing homework :P
Remove the setContentView(horiz); horiz is already a part of the activity's content view.
Your approach is wrong, you want to fill your layout with a lot of information by creating multiple textviews to show information, what you need is a list view and a custom list adapter, so you can get from your shared preferences info you will save in a list, and then pass it to the adapter so the adapter can build all the views you want and doing it better and easier than your approach.
First answer: horiz already has a parent (it's already part of the contentview which you set). Remove setContentView(horiz) To answer your second question: SharedPreferences sp = getSharedPreferences("details",1); int numofaccounts = sp.getInt("numofaccouns",0); Which means you get sharedpreferences (details) with entry numofaccouns. That one doesnt exist, however, because you never save it. You only get a non-existing entry, and if that one doesnt exist, you default it to 0. The forloop is initialized like for (int i = 0; i <= numofaccouns; i++) which means you always hit index i == 0, because numofaccouns is always 0 final String SHARED_PREFS = "details"; final String NUMBER_OF_ACCOUNTS = "numberOfAccounts"; final int NUMBER_OF_ACCOUNTS_DEFAULT = 10; int numberOfAccounts = 75; //to save into sharedpreferences: getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit().put(NUMBER_OF_ACCOUNTS, numberOfAccounts).commit(); //to retrieve that value: numberOfAccounts = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).getInt(NUMBER_OF_ACCOUNTS, NUMBER_OF_ACCOUNTS_DEFAULT); saving all the accounts et cetera can be done in exactly the same manner as the example given above.