NullException on Bitmap ,bitmaps is getting null value - image

I'm trying to get multiple images from the gallery, show it in >Recyclerview, and sending it to server but showing this error >Here's my code to write the images to file,the error is at the >initialization of inputstream
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Data any THING", String.valueOf(data));
if (requestCode == ImagePicker.IMAGE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> mPaths = data.getStringArrayListExtra(ImagePicker.EXTRA_IMAGE_PATH);
Log.d("mPaths MainActivity", String.valueOf(mPaths));
for (int i = 0; i < mPaths.size(); i++) {
files.add(new File(mPaths.get(i)));
}
if (inputStream==null) {
for (int i = 0; i < files.size(); i++) {
try {
inputStream = getContentResolver().openInputStream(Uri.fromFile( files.get(i)));
Toast.makeText(this, "Inputstream"+String.valueOf(inputStream), Toast.LENGTH_SHORT).show();
bitmaps = BitmapFactory.decodeStream(inputStream);
Log.e("File", String.valueOf(files));
Log.e("stream", String.valueOf(inputStream));
editText.setText(String.valueOf(files)+String.valueOf(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("DATASSSSSSSSSSSTTTT", String.valueOf(data.getData()));
Log.e("IMages From Stream", String.valueOf(bitmaps));
Log.d("Images from Steam", String.valueOf(bitmaps));
recyclerAdapter.fileMOthod(files);
if (bitmaps != null) {
resizeIMagestoAdapter();
imageResize(bitmaps);
} else {
}
}
}
}
}

The files array has only indices 0 to files.size()-1, but your i variable goes from 0 to files.size() in the loop:
for (int i = 0; i < files.size()+1; i++)
Therefore, files.get(i) fails with the IndexOutOfBoundsException.
Index: 2, Size: 2 means that the size of files is 2 (it has only indices 0 and 1), but you are trying to access index 2.

Related

Adding Object[] method to main()

I am trying to pass this method through my main() function but The loadMap already has the bufferreader so I am trying to use that rather than creating my own new buffer reader. How can I do this?
public static void main(String args[]) {
//throw exceptions here if args is empty
filename = args[0];
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
MapIO.loadMap(filename);
launch(args);
}
/** Read information from a file created with saveMap
* #param filename Filename to read from
* #return null if unsucessful. If successful, an array of two Objects.
[0] being the Player object (if found) and
[1] being the start room.
* #detail. Do not add the player to the room they appear in, the caller
will be responsible for placing the player in the start room.
*/
public static Object[] loadMap(String filename) {
Player player = null;
try {
BufferedReader bf = new BufferedReader(
new FileReader(filename));
String line = bf.readLine();
int idcap = Integer.parseInt(line);
Room[] rooms = new Room[idcap];
for (int i = 0; i < idcap; ++i) {
line = bf.readLine();
if (line == null) {
return null;
}
rooms[i] = new Room(line);
}
for (int i = 0; i < idcap; ++i) { // for each room set up exits
line = bf.readLine();
int exitcount=Integer.parseInt(line);
for (int j=0; j < exitcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
int pos = line.indexOf(' ');
if (pos < 0) {
return null;
}
int target = Integer.parseInt(line.substring(0,pos));
String exname = line.substring(pos+1);
try {
rooms[i].addExit(exname, rooms[target]);
} catch (ExitExistsException e) {
return null;
} catch (NullRoomException e) {
return null;
}
}
}
for (int i = 0;i<idcap;++i) {
line = bf.readLine();
int itemcount = Integer.parseInt(line);
for (int j = 0; j < itemcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
Thing t = decodeThing(line, rooms[0]);
if (t == null) {
return null;
}
if (t instanceof Player) { // we don't add
player = (Player)t; // players to rooms
} else {
rooms[i].enter(t);
}
}
}
Object[] res = new Object[2];
res[0] = player;
res[1] = rooms[0];
return res;
} catch (IOException ex) {
return null;
} catch (IndexOutOfBoundsException ex) {
return null;
} catch (NumberFormatException nfe) {
return null;
}
}
You shouldn't do anything in main() other than call launch(). Move all the other startup code to your start() method. You can get the content of the args array using getParameters().getRaw():
#Override
public void start(Stage primaryStage) {
//throw exceptions here if args is empty
filename = getParameters().getRaw().get(0);
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
Object[] whateverThisThingIs = MapIO.loadMap(filename);
// Now you have access to everything you need, at the point where you need it.
// existing start() code goes here...
}
public static void main(String args[]) {
launch(args);
}

Insertion Sort for Singly Linked List [EXTERNAL]

I'm not sure where to start, but this is messy. Basically I need to write an Insertion Sort method for singly linked list - which causes enough problems, because usually for Insertion Sort - you're supposed to go through array/list elements backwards - which implementing into a singly linked list seems pointless, because the point of it - is that you're only capable of going forwards in the list and in addition to that -> I need to execute "swap" operations externally, which I do not completely understand how to perform that while using list structure.
This is my ArrayClass and Swap method that I used:
class MyFileArray : DataArray
{
public MyFileArray(string filename, int n, int seed)
{
double[] data = new double[n];
length = n;
Random rand = new Random(seed);
for (int i = 0; i < length; i++)
{
data[i] = rand.NextDouble();
}
if (File.Exists(filename)) File.Delete(filename);
try
{
using (BinaryWriter writer = new BinaryWriter(File.Open(filename,
FileMode.Create)))
{
for (int j = 0; j < length; j++)
writer.Write(data[j]);
}
}
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
}
public FileStream fs { get; set; }
public override double this[int index]
{
get
{
Byte[] data = new Byte[8];
fs.Seek(8 * index, SeekOrigin.Begin);
fs.Read(data, 0, 8);
double result = BitConverter.ToDouble(data, 0);
return result;
}
}
public override void Swap(int j, double a)
{
Byte[] data = new Byte[16];
BitConverter.GetBytes(a).CopyTo(data, 0);
fs.Seek(8 * (j + 1), SeekOrigin.Begin);
fs.Write(data, 0, 8);
}
}
And this is my Insertion Sort for array:
public static void InsertionSort(DataArray items)
{
double key;
int j;
for (int i = 1; i < items.Length; i++)
{
key = items[i];
j = i - 1;
while (j >= 0 && items[j] > key)
{
items.Swap(j, items[j]);
j = j - 1;
}
items.Swap(j, key);
}
}
Now I somehow have to do the same exact thing - however using Singly Linked List, I'm given this kind of class to work with (allowed to make changes):
class MyFileList : DataList
{
int prevNode;
int currentNode;
int nextNode;
public MyFileList(string filename, int n, int seed)
{
length = n;
Random rand = new Random(seed);
if (File.Exists(filename)) File.Delete(filename);
try
{
using (BinaryWriter writer = new BinaryWriter(File.Open(filename,
FileMode.Create)))
{
writer.Write(4);
for (int j = 0; j < length; j++)
{
writer.Write(rand.NextDouble());
writer.Write((j + 1) * 12 + 4);
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
}
public FileStream fs { get; set; }
public override double Head()
{
Byte[] data = new Byte[12];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(data, 0, 4);
currentNode = BitConverter.ToInt32(data, 0);
prevNode = -1;
fs.Seek(currentNode, SeekOrigin.Begin);
fs.Read(data, 0, 12);
double result = BitConverter.ToDouble(data, 0);
nextNode = BitConverter.ToInt32(data, 8);
return result;
}
public override double Next()
{
Byte[] data = new Byte[12];
fs.Seek(nextNode, SeekOrigin.Begin);
fs.Read(data, 0, 12);
prevNode = currentNode;
currentNode = nextNode;
double result = BitConverter.ToDouble(data, 0);
nextNode = BitConverter.ToInt32(data, 8);
return result;
}
To be completely honest - I'm not sure neither how I'm supposed to implement Insertion Sort nor How then translate it into an external sort. I've used this code for not external sorting previously:
public override void InsertionSort()
{
sorted = null;
MyLinkedListNode current = headNode;
while (current != null)
{
MyLinkedListNode next = current.nextNode;
sortedInsert(current);
current = next;
}
headNode = sorted;
}
void sortedInsert(MyLinkedListNode newnode)
{
if (sorted == null || sorted.data >= newnode.data)
{
newnode.nextNode = sorted;
sorted = newnode;
}
else
{
MyLinkedListNode current = sorted;
while (current.nextNode != null && current.nextNode.data < newnode.data)
{
current = current.nextNode;
}
newnode.nextNode = current.nextNode;
current.nextNode = newnode;
}
}
So if someone could maybe give some kind of tips/explanations - or maybe if you have ever tried this - code examples how to solve this kind of problem, would be appreciated!
I actually have solved this fairly recently.
Here's the code sample that you can play around with, it should work out of the box.
public class SortLinkedList {
public static class LinkListNode {
private Integer value;
LinkListNode nextNode;
public LinkListNode(Integer value, LinkListNode nextNode) {
this.value = value;
this.nextNode = nextNode;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public LinkListNode getNextNode() {
return nextNode;
}
public void setNextNode(LinkListNode nextNode) {
this.nextNode = nextNode;
}
#Override
public String toString() {
return this.value.toString();
}
}
public static void main(String...args) {
LinkListNode f = new LinkListNode(12, null);
LinkListNode e = new LinkListNode(11, f);
LinkListNode c = new LinkListNode(13, e);
LinkListNode b = new LinkListNode(1, c);
LinkListNode a = new LinkListNode(5, b);
print(sort(a));
}
public static void print(LinkListNode aList) {
LinkListNode iterator = aList;
while (iterator != null) {
System.out.println(iterator.getValue());
iterator = iterator.getNextNode();
}
}
public static LinkListNode sort(LinkListNode aList){
LinkListNode head = new LinkListNode(null, aList);
LinkListNode fringePtr = aList.getNextNode();
LinkListNode ptrBeforeFringe = aList;
LinkListNode findPtr;
LinkListNode prev;
while(fringePtr != null) {
Integer valueToInsert = fringePtr.getValue();
findPtr = head.getNextNode();
prev = head;
while(findPtr != fringePtr) {
System.out.println("fringe=" + fringePtr);
System.out.println(findPtr);
if (valueToInsert <= findPtr.getValue()) {
LinkListNode tmpNode = fringePtr.getNextNode();
fringePtr.setNextNode(findPtr);
prev.setNextNode(fringePtr);
ptrBeforeFringe.setNextNode(tmpNode);
fringePtr = ptrBeforeFringe;
break;
}
findPtr = findPtr.getNextNode();
prev = prev.getNextNode();
}
fringePtr = fringePtr.getNextNode();
if (ptrBeforeFringe.getNextNode() != fringePtr) {
ptrBeforeFringe = ptrBeforeFringe.getNextNode();
}
}
return head.getNextNode();
}
}
From a high level, what you are doing is you are keeping track of a fringe ptr, and you are inserting a node s.t. the it is in the correct spot in the corresponding sublist.
For instance, suppose I have this LL.
3->2->5->4
The first iteration, I have fringePtr at 2, and I want to insert 2 somewhere in the sublist that's before the fringe ptr, so I basically traverse starting from head going to the fringe ptr until the value is less than the current value. I also have a previous keeping track of the previous ptr (to account for null, I have a sentinel node at the start of my traversal so I can insert it at the head).
Then, when I see that it's less than the current, I know I need to insert it next to the previous, so I have to:
use a temporary ptr to keep track of my previous's current next.
bind previuos's next to my toInsert node.
bind my toInsert node's next to my temp node.
Then, to continue, you just advance your fringe ptr and try again, basically building up a sublist that is sorted as you move along until fringe hits the end.
i.e. the iterations will look like
1. 3->2->5->4
^
2. 2->3->5->4
^
3. 2->3->5->4
^
4. 2->3->4->5 FIN.

How can I fix my fetch() method so it doesn't return an NullPointerException error?

public class ListingStudent{
private Listing[] data;
private int next;
private int size;
public ListingStudent()
{
next=0;
size=100;
data= new Listing[size];
}
public boolean insert(Listing newListing)
{
if(next>= size)
return false;
data[next]= newListing.deepCopy();
if(data[next] == null)
return false;
next= next + 1;
return true;
}
public Listing fetch(String targetKey){
Listing student;
Listing temp;
int i=0;
while(i < next && !(data[i].compareTo(targetKey) == 0))
{
i++;
}
if(i == next)
return null;
student= data[i].deepCopy();
if(i != 0)
{
temp = data[i-1];
data[i-1] = data[i];
data[i] = temp;
}
return student;
}
public boolean delete(String targetKey)
{
int i = 0;
while(i < next && !(data[i].compareTo(targetKey)==0))
{
i++;
}
if(i == next)
return false;
data[i] = data[next-1];
data[next-1] = null;
next = next - 1;
return true;
}
public boolean update(String targetKey, Listing newListing)
{
if(delete(targetKey) == false)
return false;
else if(insert(newListing) == false)
return false;
else
return true;
}
public void showAll()
{
for(int i=0; i < next; i++)
System.out.println(data[i].toString());
}
public static void main(String[] args){
ListingStudent obj1 = new ListingStudent();
Listing temp;
Listing l1 = new Listing("Terrence", 1, 3.45);
Listing l2 = new Listing("Roberta", 2, 2.15);
Listing l3 = new Listing("George", 3, 1.50);
System.out.println(obj1.insert(l1));
System.out.println(obj1.insert(l2));
System.out.println(obj1.insert(l3));
temp = obj1.fetch("Roberta");
System.out.println(temp.toString());
temp = obj1.fetch("Terrence");
System.out.println(temp.toString());
System.out.println(obj1.delete("George"));
System.out.println(obj1.delete("Terrence"));
System.out.println(obj1.fetch("Terrence"));
System.out.println(obj1.update("George", l2 ));
obj1.insert(l1);
System.out.println(obj1.update("Terrence", l3 ));
temp= obj1.fetch("Terrence");
System.out.println(temp.toString());
temp = obj1.fetch("George");
System.out.println(temp.toString());
}
}
Hello Everyone,
My application consists of two classes: one is called Listing which is defined in a separate and the other one is posted here. The basic working of my application is it should be able to insert, fetch, delete, and update listings into an array. I have been trying for hours to figure out which one of my fetch calls returns a NullPointerException. I understand what the exception means, but shouldn't it display what I want instead of the type error. Can someone please help understand my error in my java application. Thanks! Here is my code.

WritableByteChannel into BLOB

I have to extend an existing source code. I have this method:
public final int copyStreams(InputStream in, OutputStream out, long sizeLimit) throws IOException
{
int byteCount = 0;
IOException error = null;
long totalBytesRead = 0;
try
{
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1)
{
// We are able to abort the copy immediately upon limit violation.
totalBytesRead += bytesRead;
if (sizeLimit > 0 && totalBytesRead > sizeLimit)
{
StringBuilder msg = new StringBuilder();
msg.append("Content size violation, limit = ")
.append(sizeLimit);
throw new ContentLimitViolationException(msg.toString());
}
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
try
{
out.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
}
if (error != null)
{
throw error;
}
return byteCount;
}
and this is my main class:
public static void main (String[] arg)
{
InputStream in = new FileInputStream("pathToMyFile");
ContentLimitProvider contentLimitProvider = getContentLimitProvider();
final long sizeLimit = contentLimitProvider.getSizeLimit();
int byteCount = sizeLimitedStreamCopier.copyStreams(in, out, sizeLimit);
return byteCount;
}
and this is the method I'm forced to use to build my outputStream
public OutputStream getContentOutputStream() throws ContentIOException
{
try
{
WritableByteChannel channel = getWritableChannel();
OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
// done
return is;
}
catch (Throwable e)
{
throw new ContentIOException("Failed to open stream onto channel: \n" +
" writer: " + this,
e);
}
}
How can I develop a getWritableChannel() method in order to write into a BLOB field inside a Database DataTable (RBDMS). I'd like to use Spring if it is necessary.

Blackberry Listfield with Live Image

I want to display a listfield with live image in all rows of the listfield
check out this
also use the following code for displaying live images:
public static String getImageFromUrl(String url) {
//Image img = null;
String imageData = null;
try
{
imageData = getDataFromUrl(url);
//img = Image.createImage(imageData.getBytes(), 0,imageData.length() );
}
catch(Exception e1) {
e1.printStackTrace();
}
return imageData;
}
public static String getDataFromUrl(String url)
throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0 ;
int ch = 0;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
//HttpConnection httpConn;
c = (HttpConnection)connDesc.getConnection();
}
// c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if( len != -1) {
// Read exactly Content-Length bytes
for(int i =0 ; i < len ; i++ )
if((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
//Read until the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available() ;
b.append((char)ch);
}
}
is.close();
c.close();
return b.toString();
}
Hope this will help you.

Resources