Hi Now trying to create folder in my gallery....normally my grid view display images in separately but I need folder in my gallery. so, I am using file class....if i run my project log cat indicate error how to solve these error? please check my coding also.....
ImageViewExample.java
package ImageViewExample.ImageViewExample;
import java.io.File;
import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class ImageViewExample extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor;
private int image_column_index, actual_image_column_index;
GridView imagegrid;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Thumbnails._ID };
imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(new ImAdapterh(this));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,
int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImAdapterh extends BaseAdapter{
File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
int count=dir.list().length;
String[] fileNames = dir.list();
private Context mContext;
public ImAdapterh(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
for(String bitmapFileName : fileNames)
{
if (convertView == null)
{ // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new Gallery.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" +
bitmapFileName);
System.out.println(dir);
imageView.setImageBitmap(bmp);
}else
{
imageView = (ImageView) convertView;
}
}
return imageView;
}
}}
Logcat Error:
04-29 14:56:23.011: DEBUG/AndroidRuntime(415): >>>>>>>>>>>>>> AndroidRuntime START
<<<<<<<<<<<<<<
04-29 14:56:23.021: DEBUG/AndroidRuntime(415): CheckJNI is ON
04-29 14:56:23.402: DEBUG/AndroidRuntime(415): --- registering native functions ---
04-29 14:56:24.781: DEBUG/AndroidRuntime(415): Shutting down VM
04-29 14:56:24.791: DEBUG/dalvikvm(415): Debugger has detached; object registry had 1
entries
04-29 14:56:24.821: INFO/AndroidRuntime(415): NOTE: attach of thread 'Binder Thread
#3' failed
04-29 14:56:25.761: DEBUG/AndroidRuntime(423): >>>>>>>>>>>>>> AndroidRuntime START
<<<<<<<<<<<<<<
04-29 14:56:25.761: DEBUG/AndroidRuntime(423): CheckJNI is ON
04-29 14:56:26.141: DEBUG/AndroidRuntime(423): --- registering native functions ---
04-29 14:56:27.552: INFO/ActivityManager(66): Starting activity: Intent {
act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000
cmp=ImageViewExample.ImageViewExample/.ImageViewExample }
04-29 14:56:28.182: DEBUG/AndroidRuntime(423): Shutting down VM
04-29 14:56:28.232: DEBUG/dalvikvm(423): Debugger has detached; object registry had 1
entries
04-29 14:56:28.291: INFO/ActivityManager(66): Start proc
ImageViewExample.ImageViewExample for activity
ImageViewExample.ImageViewExample/.ImageViewExample: pid=430 uid=10050 gids={}
04-29 14:56:28.312: INFO/AndroidRuntime(423): NOTE: attach of thread 'Binder Thread
#3' failed
04-29 14:56:29.641: DEBUG/AndroidRuntime(430): Shutting down VM
04-29 14:56:29.641: WARN/dalvikvm(430): threadid=1: thread exiting with uncaught
exception (group=0x4001d800)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): FATAL EXCEPTION: main
04-29 14:56:29.711: ERROR/AndroidRuntime(430): java.lang.RuntimeException: Unable to
start activity
ComponentInfo{ImageViewExample.ImageViewExample/ImageViewExample.
ImageViewExample.ImageViewExample}: java.lang.NullPointerException
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.os.Handler.dispatchMessage(Handler.java:99)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.os.Looper.loop(Looper.java:123)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.ActivityThread.main(ActivityThread.java:4627)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
java.lang.reflect.Method.invokeNative(Native Method)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
java.lang.reflect.Method.invoke(Method.java:521)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
dalvik.system.NativeStart.main(Native Method)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): Caused by:
java.lang.NullPointerException
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
ImageViewExample.ImageViewExample.ImageViewExample$ImAdapterh.<init>
(ImageViewExample.java:73)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
ImageViewExample.ImageViewExample.ImageViewExample.init_phone_image_grid
(ImageViewExample.java:47)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
ImageViewExample.ImageViewExample.ImageViewExample.onCreate
(ImageViewExample.java:36)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2627)
04-29 14:56:29.711: ERROR/AndroidRuntime(430): ... 11 more
04-29 14:56:29.751: WARN/ActivityManager(66): Force finishing activity
ImageViewExample.ImageViewExample/.ImageViewExample
04-29 14:56:30.292: WARN/ActivityManager(66): Activity pause timeout for
HistoryRecord{4406aab0 ImageViewExample.ImageViewExample/.ImageViewExample}
04-29 14:56:36.701: DEBUG/dalvikvm(189): GC_EXPLICIT freed 162 objects / 7136 bytes in
121ms
04-29 14:56:41.568: WARN/ActivityManager(66): Activity destroy timeout for
HistoryRecord{4406aab0 ImageViewExample.ImageViewExample/.ImageViewExample}
please help me.....
The problem is almost certainly this line:
int count=dir.list().length;
The chain of logic that demonstrates that it has to be that line is follows:
The statement that creates the File object can't throw an exception in the ImAdapterh constructor itself.
This means that dir must be non-null.
This means that dir.list() won't throw an exception in the ImAdapterh constructor.
This just leaves the dereferencing of the String[] reference to get the length value as the culprit.
Finally, the null pointer can be explained by the fact that File.list() returns null if the File (in this case dir) does not exists or doesn't denote a directory ... as per the File.list() javadoc.
Null Pointer exception in your adapter class.
File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
int count=dir.list().length;
String[] fileNames = dir.list();
check above lines...that a value returning null.
Related
I am trying to pass a String form one activity to another in my app, however I keep getting a null pointer error. This is what shows up in my LogCat:
12-29 02:49:03.256: D/(663): HostConnection::get() New Host Connection established 0x96cb850, tid 663
12-29 02:49:06.288: W/KeyCharacterMap(663): No keyboard for id 0
12-29 02:49:06.288: W/KeyCharacterMap(663): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
12-29 02:49:09.600: D/AndroidRuntime(663): Shutting down VM
12-29 02:49:09.600: W/dalvikvm(663): threadid=1: thread exiting with uncaught exception (group=0xb5f444f0)
12-29 02:49:09.604: E/AndroidRuntime(663): FATAL EXCEPTION: main
12-29 02:49:09.604: E/AndroidRuntime(663): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld3/com.example.helloworld3.FloorPlan}: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Looper.loop(Looper.java:130)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invoke(Method.java:507)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-29 02:49:09.604: E/AndroidRuntime(663): at dalvik.system.NativeStart.main(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): Caused by: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at com.example.helloworld3.FloorPlan.onCreate(FloorPlan.java:24)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-29 02:49:09.604: E/AndroidRuntime(663): ... 11 more
12-29 02:49:12.316: D/(677): HostConnection::get() New Host Connection established 0x96c5790, tid 677
This is my ManActivity.java:
package com.example.helloworld3;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract.RawContacts.Data;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText destination = (EditText)findViewById(R.id.roomdinput);
final Button floorPlan = (Button)findViewById(R.id.floorPlanButton);
floorPlan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
String roomName = destination.getText().toString();
Bundle myb = new Bundle();
myb.putString("key1", roomName);
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb);
startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is my FloorPan.java:
package com.example.helloworld3;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FloorPlan extends Activity{
DrawView2 drawView;
String roomName2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.floorplan);
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");
drawView = new DrawView2(this);
drawView.setBackgroundResource(R.drawable.tait1st);
setContentView(drawView);
}
public class DrawView2 extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
public String getRoomName(){
return roomName2;
}
public void setCoordinates(){
if(roomName2 == "C154"){
ux =90;
dx = 250;
rx = 90;
lx = 400;
}else {
ux =76;
dx = 98;
rx = 140;
lx = 300;
}
};
public DrawView2(Context context) {
super(context);
paint.setColor(Color.RED);
//roomName2 = drawView.getTag();
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawLine(ux, dx , rx, lx, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
}
Thank you for all your help!
I think , This line in OnClickListener of floorPlan in your MainActivity causing problem :
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
putString method is correct. It's inherited from android.os.BaseBundle.
The logcat shows your bundle get from intent.getExtras() is null:
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");//here myb2 is null
Maybe you should override onNewIntent to setIntent:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
Why you have started activity 2 times in below code ?
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb); startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN")); // this intent doesnt`t have bundle
This might be the reason which lead where Bundle object is null in intent and causing nullpointerexception.
I am getting a NullPointerException. Below you can find my Logcat and the relevant code.
Logcat:
12-23 00:17:35.330: E/AndroidRuntime(2019): FATAL EXCEPTION: main
12-23 00:17:35.330: E/AndroidRuntime(2019): Process: com.android.timesheet, PID: 2019
12-23 00:17:35.330: E/AndroidRuntime(2019): java.lang.NullPointerException
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.timesheet.adapter.CustomCursorAdapter$1.onClick(CustomCursorAdapter.java:54)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View.performClick(View.java:4438)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View$PerformClick.run(View.java:18422)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.handleCallback(Handler.java:733)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.dispatchMessage(Handler.java:95)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Looper.loop(Looper.java:136)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.app.ActivityThread.main(ActivityThread.java:5017)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invoke(Method.java:515)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-23 00:17:35.330: E/AndroidRuntime(2019): at dalvik.system.NativeStart.main(Native Method)
CustomCursorAdapter.java:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.android.timesheet.ModifyMember;
import com.android.timesheet.R;
public class CustomCursorAdapter extends CursorAdapter {
Button delete_btn;
TextView memID_tv, memName_tv;
#SuppressWarnings("deprecation")
public CustomCursorAdapter(Activity context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
memID_tv = (TextView)v.findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
String memberID_val = memID_tv.getText().toString();; ---->54th Line
String memberName_val = memName_tv.getText().toString();
Intent i = new Intent(context,
ModifyMember.class);
i.putExtra("memberName", memberName_val);
i.putExtra("memberID", memberID_val);
((Activity)context).startActivity(i);
}
});
}
}
I am using a delete button to delete all the listview row items. At that point I am getting the NullPointerException.
Use view(view of row) instead of v parameter of onClick method which is view of Button :
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setTag(view);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowview=(View)v.getTag();
memID_tv = (TextView)rowview.findViewById(R.id.member_id);
memName_tv = (TextView)rowview.findViewById(R.id.member_name);
}
});
Use view instead of v
memID_tv = (TextView)view.findViewById(R.id.member_id);
In bindview try this-
if (view == null) {
view = inflater.inflate(R.layout.single_row_item, parent, null);
}
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
.
.
.
you are getting the view from clicked view, but you have to get the views from the root view.
memID_tv = (TextView)v. findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
change these lines into this:
memID_tv = (TextView)view. findViewById(R.id.member_id);
memName_tv = (TextView)view.findViewById(R.id.member_name);
I am stuck trying to reading from a .txt file a name and last name into a java application, I have tryed on first method with AssetManager but my application Crash when I enter it.
The second method is with inputstream but I get 3 errors:
Description Resource Path Location Type
ByteArrayOutputStream cannot be resolved to a type MainActivity.java /MyInfo/src/com/example/myinfo line 64 Java Problem
ByteArrayOutputStream cannot be resolved to a type MainActivity.java /MyInfo/src/com/example/myinfo line 64 Java Problem
dummytext cannot be resolved or is not a field MainActivity.java /MyInfo/src/com/example/myinfo line 55 Java Problem
MainActivity.java
package com.example.myinfo;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.content.res.AssetManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
TextView name = (TextView) findViewById(R.id.name);
AssetManager assetManager = getAssets();
InputStream input;
try {
input = assetManager.open("info.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
nume.setText(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView dummytext = (TextView) findViewById(R.id.dummytext);
dummytext.setText(readText());
}
private String readText() {
InputStream inputStream = getResources().openRawResource(R.raw.dummytext);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while(i!=-1){
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
and my XML is this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myinfo.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="87dp"
android:text="Adauga Fisier" />
<TextView
android:id="#+id/dummytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nume"
android:layout_below="#+id/nume"
android:layout_marginTop="29dp"
android:text="Prenume"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/button1"
android:layout_marginRight="14dp"
android:layout_marginTop="65dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
I don't understand what I did wrong.
When I run the code that is now in Comments I notice that I get in Logcat NullPointerException.
LogCat:
04-07 10:06:11.298: I/dalvikvm(275): Could not find method android.content.pm.PackageManager.getActivityLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.298: W/dalvikvm(275): VFY: unable to resolve virtual method 318: Landroid/content/pm/PackageManager;.getActivityLogo (Landroid/content/ComponentName;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.298: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x008b
04-07 10:06:11.308: I/dalvikvm(275): Could not find method android.content.pm.ApplicationInfo.loadLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.308: W/dalvikvm(275): VFY: unable to resolve virtual method 314: Landroid/content/pm/ApplicationInfo;.loadLogo (Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.308: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x0099
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x008e-0092 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x009c-00a0 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.488: D/AndroidRuntime(275): Shutting down VM
04-07 10:06:11.488: W/dalvikvm(275): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-07 10:06:11.498: E/AndroidRuntime(275): FATAL EXCEPTION: main
04-07 10:06:11.498: E/AndroidRuntime(275): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myinfo/com.example.myinfo.MainActivity}: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.os.Looper.loop(Looper.java:123)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-07 10:06:11.498: E/AndroidRuntime(275): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): at java.lang.reflect.Method.invoke(Method.java:521)
04-07 10:06:11.498: E/AndroidRuntime(275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-07 10:06:11.498: E/AndroidRuntime(275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-07 10:06:11.498: E/AndroidRuntime(275): at dalvik.system.NativeStart.main(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): Caused by: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275): at com.example.myinfo.MainActivity.onCreate(MainActivity.java:42)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-07 10:06:11.498: E/AndroidRuntime(275): ... 11 more
04-07 10:06:18.688: I/Process(275): Sending signal. PID: 275 SIG: 9
use this code
`InputStream input;
AssetManager assetManager = getAssets();
try {
input = assetManager.open("helloworld.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
dummytext.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
`
This code open an InputStream for the file from assets manager, get size from file content, allocate byte buffer with this size and read file in this buffer, after this create new string from buffer and set this string to your textview
I am new to Android.
Trying to show a dialog on press of a button like below using DialogFragments
File : Dialog2/LoginDialog.java
package com.kartnet.Dialog2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.DialogInterface;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.util.Log;
public class LoginDialog extends DialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder ad_builder = new AlertDialog.Builder(getActivity());
//ad_builder.setMessage(R.string.login_dialog);
DialogInterface.OnClickListener ad_listener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg1, int id) {
final String tag = "CustomDlg";
Log.d(tag, id + " clicked");
}
};
ad_builder.setTitle(R.string.btn_dialog_custom_title);
LayoutInflater linf = getActivity().getLayoutInflater();
ad_builder.setView(linf.inflate(R.layout.dialog_signin, null));
ad_builder.setNegativeButton("Cancel", ad_listener);
ad_builder.setPositiveButton("Ok", ad_listener);
return ad_builder.create();
}
}
File : Dialog2/Dialog2App.java
package com.kartnet.Dialog2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.DialogInterface;
import android.app.DialogFragment;
import android.app.AlertDialog;
import android.util.Log;
public class Dialog2App extends Activity
{
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void displayDialogCustom(View v)
{
LoginDialog ld = new LoginDialog(); /*<<=== FAILS with runtime exception */
// ld.show(getFragmentManager(), "login_dialog");
} /* displayCustomDialog */
}
Why should it fail at runtime, with no errors during compile time? Also, since both files are declared to be in the same package (com.kartnet.Dialog2), is there anything special I need to get these two java files to be in the application?
Here is what the error displayed
I/ActivityManager( 69): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.kartnet.Dialog2/.Dialog2App } from pid 210
I/ActivityManager( 69): Start proc com.kartnet.Dialog2 for activity com.kartnet.Dialog2/.Dialog2App: pid=1328 uid=10034 gids={1015}
W/dalvikvm( 1328): Unable to resolve superclass of Lcom/kartnet/Dialog2/LoginDialog; (7)
W/dalvikvm( 1328): Link of class 'Lcom/kartnet/Dialog2/LoginDialog;' failed
E/dalvikvm( 1328): Could not find class 'com.kartnet.Dialog2.LoginDialog', referenced from method com.kartnet.Dialog2.Dialog2App.displayDialogCustom
W/dalvikvm( 1328): VFY: unable to resolve new-instance 25 (Lcom/kartnet/Dialog2/LoginDialog;) in Lcom/kartnet/Dialog2/Dialog2App;
D/dalvikvm( 1328): VFY: replacing opcode 0x22 at 0x0000
D/dalvikvm( 1328): VFY: dead code 0x0002-0005 in Lcom/kartnet/Dialog2/Dialog2App;.displayDialogCustom (Landroid/view/View;)V
I/ActivityManager( 69): Displayed com.kartnet.Dialog2/.Dialog2App: +1s956ms
D/dalvikvm( 317): GC_EXPLICIT freed 19K, 55% free 2588K/5703K, external 1625K/2137K, paused 3208ms
D/AndroidRuntime( 1328): Shutting down VM
W/dalvikvm( 1328): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime( 1328): FATAL EXCEPTION: main
E/AndroidRuntime( 1328): java.lang.IllegalStateException: Could not execute method of the activity
E/AndroidRuntime( 1328): at android.view.View$1.onClick(View.java:2144)
E/AndroidRuntime( 1328): at android.view.View.performClick(View.java:2485)
E/AndroidRuntime( 1328): at android.view.View$PerformClick.run(View.java:9080)
E/AndroidRuntime( 1328): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 1328): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 1328): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 1328): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime( 1328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime( 1328): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 1328): Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1328): at android.view.View$1.onClick(View.java:2139)
E/AndroidRuntime( 1328): ... 11 more
E/AndroidRuntime( 1328): Caused by: java.lang.NoClassDefFoundError: com.kartnet.Dialog2.LoginDialog
E/AndroidRuntime( 1328): at com.kartnet.Dialog2.Dialog2App.displayDialogCustom(Dialog2App.java:104)
E/AndroidRuntime( 1328): ... 14 more
Based on the attached log, it appears you're trying to run the code on an older device which does not offer native support to Fragments:
Unable to resolve superclass of Lcom/kartnet/Dialog2/LoginDialog;
Above basically means that android.app.DialogFragment could not be resolved, which will happen on pre-Honeycomb (< Android 3.0 / API level 11) devices. You were probably looking for the backwards compatible Fragment classes that are part of the support library (in the android.support.v4.app.* package).
To migrate your code to the classes in the support libary, you should:
Set up the support library.
Change all android.app.DialogFragment references to android.support.v4.app.DialogFragment (and also any other Fragment classes you may be using).
Change your Activity to a FragmentActivity (also located in the support libary).
Use this dialog manager to display simple dialogs.
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
In your activity you can use this
alert.showAlertDialog(MainActivity.this,"Header","Message", false);
Try this:
Properties->Java Build Path->Order and Export and check Android Private Libraries
You can try to create the dialog before you return it with
Dialog d = ad_builder.create();
return d;
to see if it fail to create the dialog.
DialogFragment are singletons, so you cannot do:
LoginDialog ld = new LoginDialog(); /*<<=== FAILS with runtime exception */
you should use LoginDialog.instantiate(...) method
I have this code for an expandable list, I want to have a checkbox in the childgroups of the list view, and check if one of the checkboxes is checked.
The problem is that when I check if the checkbox is checked I get a NULL Pointer Exception.
Can you please tell me whats wrong?
here's my code - I've edited the code to inflate a view of the child_row.xml that holds that checkbox but I still get that null pointer, what am I doing wrong?!?!
package send.Shift;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
public class Shifts extends ExpandableListActivity implements
OnCheckedChangeListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list);
SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter(
this, createGroupList(), R.layout.group_row,
new String[] { "Group Item" }, new int[] { R.id.row_name },
createChildList(), R.layout.child_row,
new String[] { "Sub Item" }, new int[] { R.id.grp_child });
getExpandableListView().setGroupIndicator(
getResources().getDrawable(R.drawable.expander_group));
ExpandableListView EX = (ExpandableListView) findViewById(android.R.id.list);
EX.setAdapter(expListAdapter);
final CheckBox childBox = (CheckBox) findViewById(R.id.childBOX);
final TextView choosenGroup = (TextView) findViewById(R.id.choosen);
LayoutInflater inflater = LayoutInflater.from(Shifts.this);
View view2 = inflater.inflate(R.layout.child_row, null);
childBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(childBox.isChecked() == true){
choosenGroup.setText("Shift Set");
}
}
});
}
Here is some of the Logcat log:
12-23 07:38:00.644: W/dalvikvm(880): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-23 07:38:00.654: E/AndroidRuntime(880): FATAL EXCEPTION: main
12-23 07:38:00.654: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to start activity ComponentInfo{send.Shift/send.Shift.Shifts}: java.lang.NullPointerException
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:99)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:123)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-23 07:38:00.654: E/AndroidRuntime(880): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 07:38:00.654: E/AndroidRuntime(880): at java.lang.reflect.Method.invoke(Method.java:507)
12-23 07:38:00.654: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-23 07:38:00.654: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-23 07:38:00.654: E/AndroidRuntime(880): at dalvik.system.NativeStart.main(Native Method)
12-23 07:38:00.654: E/AndroidRuntime(880): Caused by: java.lang.NullPointerException
12-23 07:38:00.654: E/AndroidRuntime(880): at send.Shift.Shifts.onCreate(Shifts.java:41)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-23 07:38:00.654: E/AndroidRuntime(880): ... 11 more
If you get a nullpointer on a certain line, something on that line is null. If it is the if(childBox.isChecked() line, probably childBox is null. Hard to say without the stack, but most probable cause is the line where you retrieve that checkbox.
final CheckBox childBox = (CheckBox) findViewById(R.id.childBOX);
Might be returning null, and this could be for several reasons. It could be your id is childBox instead of childBOX. Or that it is not in R.layout.list.
The best thing you can do is start debugging. What line is the error. Find the object that is null. Find out why it is null and if that is expected or not.
Instead of checking the childBox.isChecked() you can use the isChecked value. So your code would look like this:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
choosenGroup.setText("Shift Set");
}
}
Check your layout list.xml I think this layout may is missing android:id="#+id/childBOX" for Check Box or android:id="#+id/choosen" for TextView
Check the folowin sample
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/childBOX"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/choosen"/>