I Saw another questions about this problem but non of them helped.
In my app there two different ways for adding an image and displaying it inside an imageview. 1. Gallery - 2. Camera.
gallery way is working just fine.
But in Camera way (which I'm doing it with native android Camera) I have a confusing problem.
If I rotate my phone to portrait mode (so the portrait xml loads) and take the photo in portrait mode, it works fine.
If I rotate it to landscape and use use camera also in landscape, it works fine too.
now if my xml is in portrait and after going to camera I rotate it to landscape (to take a lansdcape photo) app crashes and gives me this Errors:
05-08 21:34:22.974: E/AndroidRuntime(19000): FATAL EXCEPTION: main
05-08 21:34:22.974: E/AndroidRuntime(19000): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.kpaxteam.babyalbum/com.tiktak.albums1.A2}: java.lang.NullPointerException
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.ActivityThread.deliverResults(ActivityThread.java:2918)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2970)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.ActivityThread.access$2000(ActivityThread.java:132)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1068)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.os.Looper.loop(Looper.java:150)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.ActivityThread.main(ActivityThread.java:4277)
05-08 21:34:22.974: E/AndroidRuntime(19000): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 21:34:22.974: E/AndroidRuntime(19000): at java.lang.reflect.Method.invoke(Method.java:507)
05-08 21:34:22.974: E/AndroidRuntime(19000): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-08 21:34:22.974: E/AndroidRuntime(19000): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-08 21:34:22.974: E/AndroidRuntime(19000): at dalvik.system.NativeStart.main(Native Method)
05-08 21:34:22.974: E/AndroidRuntime(19000): Caused by: java.lang.NullPointerException
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.content.ContentResolver.acquireProvider(ContentResolver.java:745)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.content.ContentResolver.query(ContentResolver.java:258)
05-08 21:34:22.974: E/AndroidRuntime(19000): at com.tiktak.babyalbum.Helper.pathgal(Helper.java:161)
05-08 21:34:22.974: E/AndroidRuntime(19000): at com.tiktak.babyalbum.Helper.resultpic(Helper.java:299)
05-08 21:34:22.974: E/AndroidRuntime(19000): at com.tiktak.albums1.A2.onActivityResult(A2.java:242)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.Activity.dispatchActivityResult(Activity.java:4053)
05-08 21:34:22.974: E/AndroidRuntime(19000): at android.app.ActivityThread.deliverResults(ActivityThread.java:2914)
My Intent for taking photo:
Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
act.startActivityForResult(cameraIntent, int2);
My ActivityResult:
else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
Helper line 299---> String capturedImageFilePath = Helper.pathgal(act, mCapturedImageURI);
bmp = Helper.decodeFile(capturedImageFilePath, act);
if(bmp != null )
{
try {
Helper.showpic(act, id1, bmp);
settings = act.getSharedPreferences(st1, 0);
settings.edit().putString(st2, capturedImageFilePath).putInt(st3, View.VISIBLE).putInt(st4, View.GONE).commit();;
img1 = (ImageView) act.findViewById(id1);
img2 = (ImageView) act.findViewById(id2);
img1.setVisibility(View.VISIBLE);
img2.setVisibility(View.GONE);
} catch (OutOfMemoryError e) {
Toast.makeText(act.getApplicationContext(), "Try Again",
Toast.LENGTH_LONG).show();
}
}
getting image file path code:
public static String pathgal(Activity act, Uri uri){
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Helper 161---> Cursor cursor = act.getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
return null;
}
any idea?
Use following code
I had same problem resolved by it`
private void dispatchTakePictureIntent() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
name=mode+"_"+img_type+"_"+timeStamp+".jpeg";
output = new File(dir,name);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(output));
startActivityForResult(cameraIntent, 1);
}
and in onActivityResult use output.getAbsolutePath()(where output is the file which we used to create uri to pass in camera intent)) to get that image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
String IMAGE_URL=output.getAbsolutePath();
}
I Should've Just add android:configChanges="orientation" in my manifest to activities.
Thanks everyvone.
Related
I am developing an app in which my requirement to select an image from the SD card and send in to IBM Waston Visual Recognition service to identify the content in the image. I am doing like this..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == MainActivity.this.RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = MainActivity.this.getContentResolver().query(selectedImage,filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
analizarImagen(picturePath);
}
}
private void analizarImagen(String path){
File image = new File(path);
System.out.println(path);
VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
service.setApiKey("api-key");
ClassifyImagesOptions options = new ClassifyImagesOptions.Builder()
.images(image)
.build();
VisualClassification result = service.classify(options).execute();
System.out.println(result.toString());
}
But when I select an image, the application crashes
Error:
02-02 03:43:49.720 3355-3355/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/23 }} to activity {com.cucea.mauricio.visual/com.cucea.mauricio.visual.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
at android.app.ActivityThread.access$1100(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:179)
at com.cucea.mauricio.visual.MainActivity.analizarImagen(MainActivity.java:84)
at com.cucea.mauricio.visual.MainActivity.onActivityResult(MainActivity.java:68)
at android.app.Activity.dispatchActivityResult(Activity.java:5192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
at android.app.ActivityThread.access$1100(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
You are hitting server from main(UI) thread which is not allowed in android. Call your analizarImagen() method in separate thread or async task.
Check this document:
https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...
I have the following code which is designed for the user to click on a button and when they click on the button, the particular string they are viewing is Favorited and stored somewhere else.
I have two questions.
One what's wrong with what I have right now? as it crashes when you click the button.
How would you go about finishing up on the load array method for the string to be loaded and saved to an array so the user could see that array later?
Thanks for your time!!
fav.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadArray("favorites");
favorites = Arrays.copyOf(favorites, favorites.length+1);
favorites[favorites.length]=display.getText().toString();
saveArray(favorites, "favorites");
}
});
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.Menu2");
startActivity(openStartingPoint);
}
});
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.Search");
startActivity(openStartingPoint);
}
});
moreapps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri
.parse("market://search?q=pub:\"Wompa\""));
startActivity(goToMarket);
}
});
}
public String[] loadArray(String arrayName) {
SharedPreferences prefs = getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
public boolean saveArray(String[] array, String arrayName) {
SharedPreferences prefs = getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
Log Cat
05-08 23:10:51.329: I/Process(495): Sending signal. PID: 495 SIG: 9
05-08 23:11:02.360: D/dalvikvm(504): GC_EXTERNAL_ALLOC freed 44K, 53% free 2553K/5379K, external 1625K/2137K, paused 221ms
05-08 23:11:08.599: D/dalvikvm(504): GC_EXTERNAL_ALLOC freed 16K, 51% free 2644K/5379K, external 2707K/3308K, paused 174ms
05-08 23:11:12.570: D/AndroidRuntime(504): Shutting down VM
05-08 23:11:12.570: W/dalvikvm(504): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-08 23:11:12.599: E/AndroidRuntime(504): FATAL EXCEPTION: main
05-08 23:11:12.599: E/AndroidRuntime(504): java.lang.NullPointerException
05-08 23:11:12.599: E/AndroidRuntime(504): at starting.rt.Base$1.onClick(Base.java:52)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.view.View.performClick(View.java:2485)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.view.View$PerformClick.run(View.java:9080)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.os.Handler.handleCallback(Handler.java:587)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.os.Handler.dispatchMessage(Handler.java:92)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.os.Looper.loop(Looper.java:123)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-08 23:11:12.599: E/AndroidRuntime(504): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 23:11:12.599: E/AndroidRuntime(504): at java.lang.reflect.Method.invoke(Method.java:507)
05-08 23:11:12.599: E/AndroidRuntime(504): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-08 23:11:12.599: E/AndroidRuntime(504): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-08 23:11:12.599: E/AndroidRuntime(504): at dalvik.system.NativeStart.main(Native Method)
05-08 23:11:17.869: I/Process(504): Sending signal. PID: 504 SIG: 9
loadArray function returns String[]. You might want to use it like:
String [] arr = loadArray("favorites");
This array can be used later as you asked in 2nd part. Hope this helps.
Update [Based on your comment]
So, if you want to grab text in TextView and wish to add it in a List/String array:
1) Try to get the String from TextView
TextView display = (TextView)findViewById(R.id.display);
String toSave = display.getText().toString();
2) Get the existing list from SharedPreferences using `loadArray':
String [] arr = loadArray("favorites");
3) Add the new String to it:
ArrayList<String> arrList = new ArrayList<String>();
for (int i=0; i<arr.length(); i++) {
arrList.add(arr[i]); //add old values to arraylist
}
// add new string to it:
arrList.add(toSave);
//Get back your array
String [] array = arrList.toArray(new String[arrList.size()]);
4) Save it Again.
saveArray(array, "favorites");
I'm trying to build a small app that takes a data file in external storage and emails it. I keep getting 'null pointer exceptions' right away in logcat and then my app dies. I can't seem to locate my exception and I am wondering if there is a way to determine the line of code that is causing this. I have the MainActivity class and then a class called SendData- the code is below. I'm new at this so any help would be greatly appreciated- thank you.
private static final String TAG = "MainActivity_ErrorLog";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
public void onStart()
{
{
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite())
{
// verify the paths
String currentDBPath = "TLC_COMMON/database.db";
String backupDBPath = "database.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists())
{
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
}
catch (Exception e)
{
// change the V below to E when complete
Log.v(TAG,"ERROR: Database file not created");
}
startActivity(intentgetData);
}
}
}
--new class
public class SendData extends Activity
{
private static final String TAG = "MainActivity";
/* Checks if external storage is available to read */
public boolean isExternalStorageReadable()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
return true;
}
return false;
}
/** Called when the user clicks the Send My Data button */
public SendData(View view)
{
// Send data by email
{
File root = Environment.getExternalStorageDirectory();
// verify it is saving as this file name; also path in previous class
String fileName = "database.db";
if (root.canWrite())
{
File attachment = new File(root, fileName);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.putExtra(android.content.Intent.EXTRA_SUBJECT, "Exercise data");
email.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"});
// is the Uri necessary?
email.putExtra(android.content.Intent.EXTRA_TEXT, Uri.fromFile(attachment));
// look at this VVV
startActivity(Intent.createChooser(email, "Send the data via Email"));}
else
{
// Change the V below to E when complete
Log.v(TAG, "Email send failed");
}
}
}
public void finish()
{
}
}
11-13 13:29:37.343: W/dalvikvm(3319): threadid=1: thread exiting with uncaught exception (group=0x418e3300)
11-13 13:29:37.343: E/AndroidRuntime(3319): FATAL EXCEPTION: main
11-13 13:29:37.343: E/AndroidRuntime(3319): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.va.datasender/com.example.va.datasender.MainActivity}: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Looper.loop(Looper.java:137)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invoke(Method.java:511)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 13:29:37.343: E/AndroidRuntime(3319): at dalvik.system.NativeStart.main(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): Caused by: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ComponentName.<init>(ComponentName.java:75)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.Intent.<init>(Intent.java:3301)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstanceImpl(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstance(Class.java:1319)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-13 13:29:37.343: E/AndroidRuntime(3319): ... 11 more
Find the lowest "Caused by" and continue down until you reach a line from your code:
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3301)
at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The <init> means you are doing something as a class variable or inside a constructor before the Activity has a valid Context... But the specific problem is on line 36.
I would guess that you are trying to create an Intent with this. Initialize your Intent inside onCreate() instead.
Found it. Change this:
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
to:
Intent intentgetData;
and inside onCreate() (or onStart() just before calling startActivity()) add:
intentgetData = new Intent(MainActivity.this, SendData.class);
Your problem comes from line 36 on your MainActivity. Check there for the problem.
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The exeption from line number 36: at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36).
Since the error log also shows android.content.Intent.<init> after the MainActivity.java:36, I would check the value for the first parameter in the following line, when instantiating intentgetData:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
Instead of having the instatiation done there, try doing it in the onStart() method just before calling startActivity(intentgetData);:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
startActivity(intentgetData);
In the previous question ive asked, ive put all the necessary catch statements to find the exception. here is another one. i am posting the questions with exceptions, because it is easy to find an error by looking at them. since i am new to android, i am posting this type of questions.please see the code below. its saying no class found exception. but i have loaded the jcifs package jcifs-1.3.17.jar. i am not getting why the exception is thrown. please see below:
code:
package com.android.accesspc;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class userpassActivity extends Activity
{
EditText userName,userPassword;
String uName,uPassword,IP,MAC;
void help(int x)
{
userName=(EditText)findViewById(R.id.userpassUsername);
uName = userName.getText().toString();
userPassword=(EditText)findViewById(R.id.userpassPassword);
uPassword = userPassword.getText().toString();
String url= "smb://" + IP + "/";
NtlmPasswordAuthentication auth;
auth= new NtlmPasswordAuthentication(null,uName, uPassword);
try
{
SmbFile a[]=(new SmbFile(url, auth)).listFiles();
switch(x)
{
case 0:
Intent intent=new Intent("com.android.accesspc.VIEW");
intent.putExtra("IP",IP);
intent.putExtra("USERNAME",uName);
intent.putExtra("PASSWORD",uPassword);
startActivity(intent);
break;
case 1:
//code to switch off the system by checking users log on
//need to communicate with darshan's program
default:
finish();
}
}
catch(Exception e)
{
Toast.makeText(this,"Username and password is invalid OR",Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Sytem may be busy OR",Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Network error",Toast.LENGTH_SHORT).show();
Toast.makeText(this,"TRY AGAIN!!",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.userpass);
final Bundle extras = getIntent().getExtras();
if(extras !=null)
{
//values from previous activity
IP = extras.getString("IPfromMacIp");
MAC = extras.getString("MACfromMacIp");
}
Button send=(Button)findViewById(R.id.userpassSendButton);
send.setOnClickListener(new
View.OnClickListener()
{
public void onClick(View v)
{
if(extras !=null)
{
help(0);
}
}
});
Button end=(Button)findViewById(R.id.userpassEndButton);
end.setOnClickListener(new
View.OnClickListener()
{
public void onClick(View v)
{
if(extras !=null)
{
help(1);
}
}
});
}
}
Exception:
05-08 17:17:42.905: E/AndroidRuntime(398): FATAL EXCEPTION: main
05-08 17:17:42.905: E/AndroidRuntime(398): java.lang.NoClassDefFoundError: jcifs.smb.NtlmPasswordAuthentication
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.accesspc.userpassActivity.help(userpassActivity.java:25)
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.accesspc.userpassActivity$1.onClick(userpassActivity.java:73)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.View.performClick(View.java:2485)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.View.onKeyUp(View.java:4257)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.widget.TextView.onKeyUp(TextView.java:4566)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.KeyEvent.dispatch(KeyEvent.java:1280)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.View.dispatchKeyEvent(View.java:3855)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789)
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1687)
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1120)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.app.Activity.dispatchKeyEvent(Activity.java:2073)
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1663)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2560)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2535)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.os.Looper.loop(Looper.java:123)
05-08 17:17:42.905: E/AndroidRuntime(398): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-08 17:17:42.905: E/AndroidRuntime(398): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 17:17:42.905: E/AndroidRuntime(398): at java.lang.reflect.Method.invoke(Method.java:507)
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-08 17:17:42.905: E/AndroidRuntime(398): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-08 17:17:42.905: E/AndroidRuntime(398): at dalvik.system.NativeStart.main(Native Method)
put the jar file under libs, not lib (change the folder name if needed)
i removed the android dependencies folder. now its working