Android - InputStream not working correctly - java

I'm trying to figure out why my inputstream isn't working correctly. I am trying to connect to a server and get a JSON string and save it into the variable inputJSON. However inputJOSN is empty because my inputstream isn't working correctly. This line of code:
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
doesn't seem to be working properly and I'm not sure why?
public class AndroidClient extends ProfileActivity {
private TextView textIn;
public Thread rt;
public Socket socket = null;
public PrintWriter outputstrwr;
public OutputStream out = null;
public DataOutputStream dataOutputStream = null;
public DataInputStream dataInputStream = null;
public InputStream inputStr = null;
private final static String LOG_TAG = AndroidClient.class.getSimpleName();
private final Handler handler = new Handler();
private List<Profile> serviceInfoList = new ArrayList<Profile>();
// Map between list position and profile
private Map<Integer, Profile> posMap = new HashMap<Integer, Profile>();
private Map<String, Integer> addressMap = new HashMap<String, Integer>();
private static String profilePicBase64Str="";
private String inputJSON = "";
private String outputJSON = "";
private String outputJSONserv = "";
private Profile p;
//String urlInputStream = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(LOG_TAG, "Before OnCreate() Try");
try {
Log.e(LOG_TAG, "In OnCreate() Try");
socket = new Socket("23.23.175.213", 9000); //Port 1337
Log.e(LOG_TAG, "Created Socket");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Log.e(LOG_TAG, "Created DataOutputStream");
dataInputStream = new DataInputStream(socket.getInputStream());
Log.e(LOG_TAG, "Created DataInputStream");
//out = new OutputStream();
out = socket.getOutputStream();
inputStr = socket.getInputStream();
//Thread readjsonthrd = new Thread(new ReadJSONThread());
//inputstrrd = new InputStreamReader(socket.getInputStream());
p = new Profile();
Log.e(LOG_TAG, "Created Profile Instance");
//Gets the local profile via JSON and converts into Profile type
Gson gson = new Gson();
Log.e(LOG_TAG, "Created Gson Instance" + "GetProfileJSONStr:" + p.getProfileJSONStr());
p = gson.fromJson(p.getProfileJSONStr(), Profile.class);
setProfile(p);
Log.e(LOG_TAG, "Converted Profile to JSON");
//Gson gson = new Gson();
Log.e(LOG_TAG, "Before: outputJSON = gson.toJson(p);");
outputJSON = gson.toJson(p).toString();
outputJSON = removeExcessStr(outputJSON);
Log.e(LOG_TAG, "ProfilePicStr Base64:"+p.getProfilePicStr());
outputJSON = outputJSON.replace("Name","name");
outputJSON = outputJSON.replace("TagLine","message");
outputJSON = outputJSON.replace("Title","title");
outputJSON = outputJSON.replace("Company", "company");
outputJSON = outputJSON.replace("Industry","industry");
outputJSON = outputJSON.replace("WhatIDo","whatido");
outputJSON = outputJSON.replace("WhoDoIWantToMeet","meetwho");
outputJSON = outputJSON.replace("WHOOZNEAR_PROFILEPIC","photo");
outputJSON = outputJSON.replaceAll("[c][o][n][t][e][n][t][:][/][/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+", getPicBase64Str()); /*"helloworld2"*/
if (!outputJSON.contains(",\"photo\":")) {
outputJSON = outputJSON.replace("}",",\"photo\":"+"\"IconnexUs\"}");
outputJSON = outputJSON.replace("}",",\"photo\":"+"\""+getPicBase64Str()+"\"}");
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"}");
}
else {
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"");
}
outputJSONserv = "{\"to\":\"broadcast\",\"type\":\"1\",\"payload\":"+outputJSON+"}";
Log.e(LOG_TAG, "Created outputJSON:" + outputJSON);
Log.e(LOG_TAG, "Created outputJSON Server:" + outputJSONserv);
JSONObject outObject = new JSONObject();
try {
outObject.put("photo", "hello");
outObject.put("type", "50");
outObject.put("payload", outputJSON);
outputJSON = gson.toJson(outObject).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Value of PROFILEPIC STRING FROM PROFILEMAP: "+profileMap.get("WHOOZNEAR_PROFILEPIC"));
p.setProfilePicStr(ConvertandSetImagetoBase64(profileMap.get("WHOOZNEAR_PROFILEPIC")));
//String headerJSON = gson.toJson(outObject).toString();
outputJSON = outputJSON.substring(nthOccurrence(outputJSON, '{', 2)-1, nthOccurrence(outputJSON, '}', 1)-1);
String input = "["+"Ryan"+"[";
//"[foo".replaceAll(Pattern.quote("["), "\"");
String result = input.replaceAll(Pattern.quote("["), "\"");
Log.e(LOG_TAG, "REGEX REPLACEALL:"+result);
outputstrwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
outputstrwr.write(outputJSONserv);
Log.e(LOG_TAG, "Base64 String:"+p.getProfilePicStr());
Log.e(LOG_TAG, "Sent dataOutputStream");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Before initEventHandlers");
initEventHandlers();
Log.e(LOG_TAG, "After initEventHandlers");
//refreshViewModels();
Log.e(LOG_TAG, "Start Repeat Thread");
rt = new Thread(new RepeatingThread());
rt.start();
Log.e(LOG_TAG, "Started Repeat Thread");
}
#Override
public void onDestroy() {
super.onDestroy();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPause(){
super.onPause();
rt.stop();
}
#Override
public void onResume(){
super.onResume();
if (rt.isAlive() == false) {
//rt.start();
}
}
#Override
public void onStop(){
super.onStop();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String removeExcessStr(String json_excess) {
//String myString = myString.replace("=\"ppshein\"", "");
String json_excess1 = json_excess.replace("\"nameValues\":{", "");
String myString = json_excess1.replace(",\"profileId\":1,\"valid\":false}", "");
return myString;
}
public static String adddblquotattr(String attr) {
String result = attr.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static String adddblquotval(String val) {
String result = val.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static int nthOccurrence(String str, char c, int n) {
int pos = str.indexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.indexOf(c, pos+1);
return pos;
}
public void setPicBase64Str(String profilePicBase64Str) {
this.profilePicBase64Str = profilePicBase64Str;
}
public String getPicBase64Str() {
return profilePicBase64Str;
}
public String ConvertandSetImagetoBase64(String imagePath) {
String base64 = null;
byte[] input = null;
try{
FileInputStream fd = new FileInputStream(imagePath);
Bitmap bmt = BitmapFactory.decodeFileDescriptor(fd.getFD());
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap tmp = ProfileActivity.scaleDownBitmap(bmt, 10, this);
tmp.compress(Bitmap.CompressFormat.JPEG, 10, stream);
input = stream.toByteArray();
base64 = Base64.encodeToString(input, Base64.DEFAULT);
//LocalProfileActivity.input = input;
}catch(Exception e){
Log.e(LOG_TAG,"[ONACTIVITYRESULT] Could not bind input to the bytearray: " + e.getMessage());
}
}
catch (Exception e){
Log.e("LocalProfile", "ConvertandSetImagetoBase64: Could not load selected profile image");
}
return base64;
}
public String getStringFromBuffer(InputStreamReader inputstrread){
BufferedReader bRead = new BufferedReader(inputstrread);
String line = null;
StringBuffer jsonText = new StringBuffer();
try {
while((line=bRead.readLine())!=null){
jsonText.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonText.toString();
}
public String ConvertByteArrayToString(byte[] b) {
// byte[] to string
String input = new String(b);
return input;
}
public byte[] ConvertStringToByteArray(String str) {
// string to byte[]
byte[] bytes = str.getBytes();
return bytes;
}
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely stream ");
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static String writeFile(Bitmap finalBitmap) {
String filePath = "";
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream outFile = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath = root+"/saved_images/"+fname;
return filePath;
}
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
private int len = 0;
private byte[] input = new byte[len];
public RepeatingThread() {
//try {
Log.e(LOG_TAG, "Before inputJSON String");
//inputJSON = dataInputStream.readUTF();
//URL url = new URL("tcp://23.23.175.213:1337");
//inputJSON = dataInputStream.readUTF();
//inputstrrd = new InputStreamReader(socket.getInputStream());
String hello = "hello world";
//String inputJSON = getStringFromBuffer(new InputStreamReader(socket.getInputStream()));
//Convert
Log.e(LOG_TAG, "After inputJSON String:" + inputJSON);
/*}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//LOOK HERE FIRST
//inputJSON is what is received back from the server - Take the inputJSON
//String and use regular expressions HERE to remove all the other characters in the
//string except the payload JSON.
//refreshViewModels(inputJSON);
}
#Override
public void run() {
try {
//outputstrwr.write(outputJSONserv); //UNCOMMENT IF NEED TO SEND DATA TO GET JSON BACK
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON:" + inputJSON);
refreshViewModels(inputJSON);
mHandler.postDelayed(this, 3000);
}
}
public void refreshViewModels(String inputJSON) {
try {
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
String[] from = new String[] { "profilePic", "neighborName",
"tagLine" };
int[] to = new int[] { R.id.avatar, R.id.username, R.id.email };
// prepare the list of all records
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
List<Profile> profiles = new ArrayList<Profile>();
// Clear the position mapping list and reset it
this.posMap.clear();
Log.i(LOG_TAG, "NEW inputJSON: " + inputJSON);
inputJSON = getPayloadStr(inputJSON);
Log.i(LOG_TAG, "NEW inputJSON2: " + inputJSON);
JSONArray profileArray = new JSONArray(inputJSON);
for (int i=0; i<profileArray.length(); i++) {
JSONObject jsonObject = profileArray.getJSONObject(i);
Gson gson = new Gson();
Profile p = gson.fromJson(gson.toJson(jsonObject).toString(), Profile.class);
profiles.add(p);
}
int pos = 0;
// Creates the fillMaps list for the listAdapter
Log.i(LOG_TAG, "Profiles size: " + profiles.size());
//showToast("Profiles size: " + profiles.size());
for (Profile p : profiles) {
// Create mapping for list adapter
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profilePic",
p.getAttributeValue("photo")== null? "Not Set" : p
.getAttributeValue("photo"));
map.put("neighborName",
p.getAttributeValue("Name") == null? "Not Set" : p
.getAttributeValue("Name"));
map.put("tagLine",
p.getAttributeValue("TagLine") == null? "Not Set" : p
.getAttributeValue("TagLine"));
fillMaps.add(map);
// Reset the postion mapping
this.posMap.put(pos++, p);
}
ListAdapter servicesListAdapter = new myAdapter(this, fillMaps,
R.layout.listitem, from, to);
servicesListView.setAdapter(servicesListAdapter);
} catch (Exception e) {
Log.e(LOG_TAG, "Error making list adapter: " + e.getMessage());
}
}
public String getPayloadStr(String profileString) {
Log.e("LOG_TAG", "Profile Str:"+profileString);
Pattern pattern = Pattern.compile(".*?payload\":(.*)\\}");
Log.e("LOG_TAG", "I got here 1");
Matcher matcher = pattern.matcher(profileString);
Log.e("LOG_TAG", "I got here 12");
//Matcher m = responseCodePattern.matcher(firstHeader);
matcher.matches();
matcher.groupCount();
//matcher.group(0);
Log.e("LOG_TAG", "I got here 2"+matcher.group(1));
return matcher.group(1);
}
private class myAdapter extends SimpleAdapter {
public myAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listitem,
null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.username))
.setText((String) data.get("neighborName"));
((TextView) convertView.findViewById(R.id.email))
.setText((String) data.get("tagLine"));
// Convert a string representing an image back to an image
String base64 = ((String)data.get("profilePic"));
byte[] picBytes = Base64.decode(base64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(picBytes, 0, picBytes.length);
//THE IF AND THE ELSE NEED TO BE SWITCHED
if (bitmap==null){
((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.btn_whooznear);
}else{
((ImageView) convertView.findViewById(R.id.avatar)).setImageBitmap(bitmap);
}
return convertView;
}
}
public void callProfileActivity(int position)
{
// Catch the case when service info is empty
if(serviceInfoList.size()==0){
return;
}
Profile profClick = posMap.get(position);
String b64Str = profClick.getAttributeValue("photo");
Intent startViewActivity = new Intent();
startViewActivity.putExtra("TransProfile", (Profile)posMap.get(position));
startViewActivity.putExtra("PhotoBase64", b64Str);
if(serviceInfoList.size()>position){
//DO SOMETHING HERE
}else{
Log.e(LOG_TAG,"Profile doesn't exist in sevice infoList? Selecting first one");
}
startViewActivity.setClass(this, ViewProfileActivity.class);
startActivity(startViewActivity);
}
/**
* Initialize the event handlers
*/
public void initEventHandlers() {
// Service List View
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
servicesListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Profile clickedProfile = posMap.get(position);
//showToast("Clicked Pos: " + position);
/*Intent intent = new Intent(ConnectActivity.this, ViewProfileActivity.class);
intent.putExtra("ClickProfile", posMap.get(position));*/
callProfileActivity(position);
}
});
}
/*#Override
public void onBackPressed() { // do something on back.
super.onBackPressed();
Intent myIntent = new Intent(AndroidClient.this, ProfileActivity.class);
startActivity(myIntent);
return;
}*/
}

Your code is rather long, so I cannot be sure of what exactly is the problem, but there is definitely an issue here:
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
If you are calling this right after sending your URL request, the server may not have had time to send the result back, so is.available() may return zero or another value less than the actual number of bytes you would hope would be available. Try code like this for reading in the file.

Related

Java: Can't convert string to array

I can't convert a string to an array!
String text = "";
String[] textsplit = {};
//Stuff
The app set the content of an online txt file in a string:
The online txt file contain: hello,my,name,is,simone
[...] //Downloading code
text = bo.toString(); //Set the content of the online file to the string
Now the string text is like this:
text = "hello,my,name,is,simone"
Now i have to convert the string to an array that must be like this:
textsplit = {"hello","my","name","is","simone"}
so the code that i use is:
textsplit = text.split(",");
But when i try to use the array the app crash! :(
For example:
textview.setText(textsplit[0]); //The text of the textview is empity
textview.setText(textsplit[1]); //The app crash
textview.setText(textsplit[2]); //The app crash
etc...
where am I wrong? thanks!
EDIT: This is the code:
new Thread() {
#Override
public void run() {
String path ="http://www.luconisimone.altervista.org/ciao.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
text = bo.toString();
testo.setText("(" + text + ")");
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// Here all variables became empity
textsplit = text.split(",");
datisplittati.setText(textsplit[0]);
Try :
String text = "hello,my,name,is,simone";
String[] textArr = text.split(Pattern.quote(","));
You can get string using AsyncTask
private class GetStringFromUrl extends AsyncTask<String, Void, String> {
ProgressDialog dialog ;
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog when downloading
dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
}
#Override
protected String doInBackground(String... params) {
// #BadSkillz codes with same changes
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(entity);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String result = total.toString();
Log.i("Get URL", "Downloaded string: " + result);
return result;
} catch (Exception e) {
Log.e("Get Url", "Error in downloading: " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO change text view id for yourself
TextView textView = (TextView) findViewById(R.id.textView1);
// show result in textView
if (result == null) {
textView.setText("Error in downloading. Please try again.");
} else {
textView.setText(result);
}
// close progresses dialog
dialog.dismiss();
}
}
and use blow line every time that you want:
new GetStringFromUrl().execute("http://www.luconisimone.altervista.org/ciao.txt");
You're using new thread to get data from an url. So in runtime, data will be asynchronous.
So when you access text variable (split it), it's still not get full value (example reason: network delay).
Try to move the function split after text = bo.toString(); , I think it will work well.

Android Show Internal Data in to textviews

I am working on an app where I need to save/read my files from Internal storage.
But it read all my data in the same TextView.
Can someone show me show,how to show the data in 2 textviews, or to show me how put the one data under the other data.
Here is my code for saving data:
private void SaveMode() {
String FILENAME ;
String Strin1= textview1.getText().toString();
String String2= textview2.getText().toString();
EditText filename1 = (EditText) findViewById(R.id.filename);
FILENAME = filename1.getText().toString();
if (FILENAME.contentEquals("")){
FILENAME = "UNTITLED";
}
String1 = textview1.getText().toString();
String2= textview2.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("Strin1.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And here is my code for read my data:
private void getFilenames() {
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
spinner.setAdapter(filenameAdapter);
}
public void SpinnerClick(View v) {
String selectFile = String.valueOf(spinner.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
showData = (TextView) findViewById(R.id.show_data);
TextView showData1 = (TextView) findViewById(R.id.show_data1);
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
}
EDIT
I tried to edit my read code like this, but with no luck
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
String[] strArray = value.split(";");
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
Edit 2
Got it to work with Shobhit Puri codes
First while saving your data you might insert a delimiter in between those two string. Make sure that delimiter is not the one expected in your textViews.
While saving:
String string3 = ";";
try {
fos.write("Strin1.getBytes());
fos.write("String3.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Then when you are trying to read it into value string, then split is using .split function. Eg:
String[] strArray = value.split(";");
strArray[0] will give first textview's sting and strArray[1] will give the second.
Update
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
try
{
FileInputStream fis = new FileInputStream(myInternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);

Why does getElementsByTag throw NullPointerException?

I'm trying to parse xml data from this URL:http://cloud.tfl.gov.uk/TrackerNet/LineStatus but am getting a NullPointerException on the line that read:
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
Before I show the code, I'd just like to say whats going on. First I download the XML file to the SDCard in
saveToSdCard();
Then I retrieve it with
getDataFromSDcard();
Here is my code:
Main Activity:
public class DashboardFragment extends SherlockFragment {
private CardUI mCardView;
String TUBE_STATUS_URL;
String KEY_ITEM = "LineStatus";
String KEY_LINE = "Line";
String KEY_NAME = "name";
String KEY_STATUS_DETAILS = "StatusDetails";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.activity_dashboard,
container, false);
// Get the URL's
TUBE_STATUS_URL = "http://cloud.tfl.gov.uk/TrackerNet/LineStatus";
// Find the cards in inflated layout
CardUI cardGroup = (CardUI) rootView.findViewById(R.id.cardsview);
fillCards(cardGroup);
DownloadFeedsTask task = new DownloadFeedsTask();
task.execute(new String[] { "" });
return rootView;
}
private void fillCards(CardUI cardGroup) {
// Fill cards with data
// init CardView
mCardView = cardGroup;
mCardView.setSwipeable(true);
// create a stack
CardStack delayStack = new CardStack();
delayStack.setTitle("Tube Lines with delays");
// add cards to stack
delayStack.add(new MyCard("Jubilee Line", MyCard.LINE_UNAVAILABLE));
delayStack.add(new MyCard("Victoria Line", MyCard.LINE_AVAILABLE));
delayStack
.add(new MyCard("Piccadilly Line", MyCard.LINE_IN_MAINTENANCE));
delayStack.add(new MyCard("Northern", MyCard.LINE_AVAILABLE));
// create a stack
CardStack activeStack = new CardStack();
activeStack.setTitle("Active Tube Lines");
// add cards to stack
activeStack.add(new MyCard("Jubilee Line", MyCard.LINE_HIDE_STATUS));
activeStack.add(new MyCard("Victoria Line", MyCard.LINE_HIDE_STATUS));
// add stack to cardView
mCardView.addStack(delayStack);
mCardView.addStack(activeStack);
// draw cards
mCardView.refresh();
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
return super.onOptionsItemSelected(item);
}
private class DownloadFeedsTask extends AsyncTask<String, Void, String> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected String doInBackground(String... urls) {
try {
saveToSdCard();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String response = "";
XMLParser parser = new XMLParser();
String xml = getDataFromSDcard(); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, e.getAttribute(KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
// adapter = new SimpleAdapter(
// mCtx,
// menuItems,
// R.layout.list_item,
// new String[] { KEY_ADVERT, KEY_CONTACT, KEY_DATE },
// new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });
return response;
}
private String getDataFromSDcard() {
// Get data from SDCard
// Find the directory for the SD Card using the API
// *Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
File file = new File(sdcard, "Folder/test.xml");
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
return text.toString();
}
private void saveToSdCard() throws IOException {
try {
URL url = new URL(TUBE_STATUS_URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(
Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory
+ "/test.xml");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getActivity(), String.valueOf(menuItems.size()),
// Toast.LENGTH_LONG).show();
// Log.d("Commuter+", String.valueOf(menuItems.size()));
}
}
}
And my XMLParser class:
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
Log.d("Commuter+", String.valueOf(doc.toString().length()));
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}
I tried fixing this by testing my code with other URLs that had XML data and it worked, but there seems to be a problem when I use this URL.

For loop does not doing my async task completely

Im doing Download All of files. What I did was for loop, unfortunately my for loop does not finish my async task it continues doing all the loop regardless if it finished the first file that was downloading. Help please.
Here is my for loop
for (int i = 0; i < id.length; i++) {
Element e = (Element)nodes.item(i);
id[i] = ""+CategoriesXMLfunctions.getValue(e, "id");
name[i] = ""+CategoriesXMLfunctions.getValue(e, "name");
image[i] = ""+CategoriesXMLfunctions.getValue(e, "image");
simage[i] = ""+CategoriesXMLfunctions.getValue(e, "simage");
download[i] = ""+CategoriesXMLfunctions.getValue(e, "download");
author[i] = ""+CategoriesXMLfunctions.getValue(e, "author");
genre[i] = ""+CategoriesXMLfunctions.getValue(e, "genre");
size[i] = ""+CategoriesXMLfunctions.getValue(e, "size");
price[i] = ""+CategoriesXMLfunctions.getValue(e, "price");
mylist.add(map);
id_all = id[i];
image_all = image[i];
dload_all = download[i];
size_all = size[i];
name_all = name[i];
String response = null;
String resstring = null;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("devid", "devid"));
String devid=null;
try {
devid = URLEncoder.encode(Global.getMac(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String nURL = "http://....url";
response = CustomHttpClient.executeHttpPost(nURL, postParameters);
resstring=response.toString();
String credit = resstring;
String priiice = price[i];
float money = Float.parseFloat(credit);
float pri = Float.parseFloat(priiice);
if(pri>money){
final AlertDialog.Builder alert = new AlertDialog.Builder(MainStore.this);
alert.setMessage("Credits not enough.");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}else{
File sd = getDir("xml",MODE_PRIVATE);
File todel = new File(sd,id[i]+".xml");
todel.delete();
String filecreat= "/"+id[i]+".xml";
File newfil = new File(sd+ filecreat);
if(newfil.exists()){
todel.delete();
}
try{
if(!newfil.exists()){
newfil.createNewFile();
}}catch(IOException e1){
}
try{
FileWriter fileWritter = new FileWriter(newfil);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("<xml>");
bufferWritter.write("<books>");
bufferWritter.write("<id>"+id[i]+"</id>");
bufferWritter.write("<name>"+name[i]+"</name>");
bufferWritter.write("<download>"+download[i]+"</download>");
bufferWritter.write("<size>"+size[i]+"</size>");
bufferWritter.write("<author>"+author[i]+"</author>");
bufferWritter.write("<genre>"+genre[i]+"</genre>");
bufferWritter.write("<new>0</new>");
bufferWritter.write("</books>");
bufferWritter.write("</xml>");
bufferWritter.close();
Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_LONG).show();
}catch(IOException e1){
e1.printStackTrace();
Toast.makeText(getApplicationContext(), "error wrting xml "+e1.toString(), Toast.LENGTH_LONG).show();
}
downloadallStarted();
downloadallfiles();
//checkdownloadall();
//downloadallFinished();
}
}catch (Exception e1){
Toast.makeText(getApplicationContext(), "Error in downloadall: " +e1.toString(), Toast.LENGTH_LONG).show();
}
}
And here is my async task
private void startDownloadall() {
String fileURL = dload_all;
fileURL = fileURL.replace(" ", "%20");
new DownloadFileAsync1().execute(fileURL);
Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String fileURL = dload_all;
fileURL = fileURL.replace(" ", "%20");
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = getDir("ebook", MODE_PRIVATE).toString();
String ebookfile = "";
//String filename = id[index];
String filename = id_all;
if(fileURL.endsWith("pdf"))
ebookfile = filename+".pdf";
else
ebookfile = filename+".epub";
bookfile = ebookfile;
Global.setBookfile(bookfile);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, ebookfile);
FileOutputStream fos = new FileOutputStream(outputFile);
lenghtOfFilee = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFilee));
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
Global.setBookfile(bookfile);
Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
checkdownloadall();
//dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
An asynchronous task runs on a background thread, so you directly access variable dload_all in function doInBackground() that is not thread safe. Maybe you can try:
private void startDownloadall() {
//String fileURL = dload_all;
//fileURL = fileURL.replace(" ", "%20");
new DownloadFileAsync1().execute(dload_all, id_all);
Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String fileURL = args[0];
fileURL = fileURL.replace(" ", "%20");
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = getDir("ebook", MODE_PRIVATE).toString();
String ebookfile = "";
//String filename = id[index];
String filename = args[1];
if(fileURL.endsWith("pdf"))
ebookfile = filename+".pdf";
else
ebookfile = filename+".epub";
bookfile = ebookfile;
Global.setBookfile(bookfile);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, ebookfile);
FileOutputStream fos = new FileOutputStream(outputFile);
lenghtOfFilee = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFilee));
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
Global.setBookfile(bookfile);
Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
checkdownloadall();
//dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}

Android: Epub file not showing images in emulator/android device

I am using http://www.siegmann.nl/epublib to read epub file. My code is mentioned below.
try {
book = epubReader.readEpub(new FileInputStream("/sdcard/EpubTesting.epub"));
Resource res;
Spine contents = book.getSpine();
List<SpineReference> spinelist = contents.getSpineReferences();
StringBuilder string = new StringBuilder();
String line = null;
int count = spinelist.size();
for (int i=0;i<count;i++){
res = contents.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = (string.append(line+"\n")).toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(linez);
s1.loadDataWithBaseURL("/sdcard/",linez, "text/html", "UTF-8",null);
}catch (FileNotFoundException e) {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(mContext, "IO Exception.", Toast.LENGTH_SHORT).show();
}
Also tried
s1.loadDataWithBaseURL("",linez, "text/html", "UTF-8",null);
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
But result is sifar. Please tell me what I have to do to show the contained images in file. I have gone through FAQ says Make a subclass of android.webkit.WebView that overloads the loadUrl(String) method in such a way that it loads the image from the Book instead of the internet. But till I don't where they extract the file how can I locate the path. Please tell me. I am very confused. Thanks in advance.
public class EpubBookContentActivity extends Activity{
private static final String TAG = "EpubBookContentActivity";
WebView webview;
Book book;
int position = 0;
String line;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
AssetManager assetManager = getAssets();
String[] files;
try {
files = assetManager.list("books");
List<String> list =Arrays.asList(files);
if (!this.makeDirectory("books")) {
debug("faild to make books directory");
}
copyBookToDevice(list.get(position));
String basePath = Environment.getExternalStorageDirectory() + "/books/";
InputStream epubInputStream = assetManager.open("books/"+list.get(position));
book = (new EpubReader()).readEpub(epubInputStream);
DownloadResource(basePath);
String linez = "";
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
linez = linez.replace("../", "");
// File file = new File(Environment.getExternalStorageDirectory(),"test.html");
// file.createNewFile();
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(linez.getBytes());
// fileOutputStream.close();
webview.loadDataWithBaseURL("file://"+Environment.getExternalStorageDirectory()+"/books/", linez, "text/html", "utf-8", null);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
}
public boolean makeDirectory(String dirName) {
boolean res;
String filePath = new String(Environment.getExternalStorageDirectory()+"/"+dirName);
debug(filePath);
File file = new File(filePath);
if (!file.exists()) {
res = file.mkdirs();
}else {
res = false;
}
return res;
}
public void debug(String msg) {
// if (Setting.isDebug()) {
Log.d("EPub", msg);
// }
}
public void copyBookToDevice(String fileName) {
System.out.println("Copy Book to donwload folder in phone");
try
{
InputStream localInputStream = getAssets().open("books/"+fileName);
String path = Environment.getExternalStorageDirectory() + "/books/"+fileName;
FileOutputStream localFileOutputStream = new FileOutputStream(path);
byte[] arrayOfByte = new byte[1024];
int offset;
while ((offset = localInputStream.read(arrayOfByte))>0)
{
localFileOutputStream.write(arrayOfByte, 0, offset);
}
localFileOutputStream.close();
localInputStream.close();
Log.d(TAG, fileName+" copied to phone");
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
Log.d(TAG, "failed to copy");
return;
}
}
private void DownloadResource(String directory) {
try {
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
Log.d(TAG, rs.getHref());
File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, rs.getHref());
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
}
}
}
For that you have to download all resources of epub files (i.e. images,stylesheet) in location where you downloaded .epub file in sdcard. please check below code to download images and css files from .epub files itself using epublib.
for that u have to send parameter of File objects where you want to store those images.
private void DownloadResource(File FileObj,String filename) {
try {
InputStream epubis = new FileInputStream(FileObj);
book = (new EpubReader()).readEpub(epubis);
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
File oppath1 = new File(directory, "Images/"
+ rs.getHref().replace("Images/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, "Styles/"
+ rs.getHref().replace("Styles/", ""));
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
Log.v("error", e.getMessage());
}
}
after this use this your code to set path of images in webview.
if stored in sd card then
s1.loadDataWithBaseURL("file:///sdcard/",linez, "text/html",null,null);
or
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
if in internal storage then
s1.loadDataWithBaseURL("file:///data/data/com.example.project/app_mydownload/",linez, "text/html",null,null);

Categories