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
Related
I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
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:5019)
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: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
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:5019)
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: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
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:5019)
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)
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful
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.
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);
i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.