I am using a spinner when selected starts an intent and the class that is started gets and XML feed and displays it.
I am trying to call a different XML file based on what is selected by the user. I am not sure how the value can be passed to my XMLfunctions.java and once selected can the other classes reference that data?
HERE is my Eclipse Package Download
My thourghts were to have a multidimensional array with the titles for the spinner and the coinsiding XML url:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class patriosar extends Activity {
private Button goButton;
private String array_spinner[];
String url = "http://www.patriotsar.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
Spinner areaspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array_spinner=new String[4];
array_spinner[0]="George Washington","gw.xml";
array_spinner[1]="BENJAMIN FRANKLIN","bf.xml";
array_spinner[2]="THOMAS JEFFERSON","tj.xml";
array_spinner[3]="PATRICK HENRY","ph.xml";
goButton = (Button)findViewById(R.id.goButton);
areaspinner = (Spinner) findViewById(R.id.areaspinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
areaspinner.setAdapter(adapter);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
areaspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = areaspinner.getSelectedItemPosition();
if(item != 0){
Intent myIntent = new Intent(patriosar.this, ShowXMLPAR.class);
startActivityForResult(myIntent, 0);
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
I then have a listener that calls an intent ShowXMLPAR.class when an item other then default is selected. The ShowXMLPAR class calls a function from XMLfunctions.java class and then shows the data that is returned. So the second value in the selected array item needs to be passed to to both pages I guess.
ShowXMLPAR.java:
package com.patriotsar;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.patriotsar.XMLfunctions;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ShowXMLPAR extends ListActivity {
private Button backButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
backButton = (Button)findViewById(R.id.backButton);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
Intent myIntent = new Intent(view.getContext(), patriosar.class);
startActivityForResult(myIntent, 0);
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "content"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
//
ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listlayout,
new String[] {"main_content", "name" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
}
}
XMLfunctions.java:
package com.patriotsar;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLfunctions {
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.patriotsar.com/patriot_quotes.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
Sorry I am still learning but am excited to get into more advanced (for me) programming. Any Help would be awesome.
As of now the app works but calls the same xml no matter what.
I'm not following your description very well, but if you are wanting to pass data between Activities via Intents then make sure the data you pass can either be included as an Extra, or if you prefer to send actual objects then make sure your objects implement the Parcelable interface.
Related
I'm trying to make an inventory apps to save item by item into internal storage. Here is my layout. The problem is it possible to save arraylist into document text file / other internal storage? Because fos.write(listitem.getBytes()); should be in Int. Here is my code from Activity2
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
public static final String extraint = "1";
public static final String namabarang = "2";
public static final String jumlahstock ="3";
public static final String FILE_NAME="example.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void onBtnClick(View view){
TextView plain1 = findViewById(R.id.NamaBarang);
TextView plain2 = findViewById(R.id.SKU);
TextView plain3 = findViewById(R.id.JumlahStok);
TextView plain4 = findViewById(R.id.HargaBeli);
TextView plain5 = findViewById(R.id.HargaJual);
Intent intent = new Intent(this,MainActivity3.class);
String x = "1";
String text = plain1.getText().toString();
FileOutputStream fos = null;
Item m1 = new Item("a","1");
Item m2 = new Item("b","2");
Item m3 = new Item("c","3");
ArrayList<Item> listitem = new ArrayList<>();
listitem.add(m1);
listitem.add(m2);
listitem.add(m3);
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(listitem.getBytes());
Toast.makeText(this,"Saved to" +getFilesDir() + "/" + FILE_NAME,Toast.LENGTH_LONG).show();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(fos != null){
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
intent.putExtra(extraint,x);
intent.putExtra(FILE_NAME,text);
intent.putExtra(namabarang,plain1.getText().toString());
intent.putExtra(jumlahstock,plain3.getText().toString());
startActivity(intent);
}
}
Here is another code from Activity 3
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListView;
import org.w3c.dom.Element;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity3 extends AppCompatActivity {
private static final String Tag = "MainAcitivity3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Log.d(Tag, "onCreate: Started.");
ListView mListView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
String[] barang = new String[20];
String[] jumlah = new String[20];
ArrayList<Item> itemlist = new ArrayList<Item>();
int loop=0;
barang[loop] = intent.getStringExtra(MainActivity2.namabarang);
jumlah[loop] = intent.getStringExtra(MainActivity2.jumlahstock);
loop++;
FileInputStream fis = null;
StringBuilder sb = new StringBuilder();
try {
fis = openFileInput(MainActivity2.FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String text;
while ((text = br.readLine()) != null){
sb.append(text).append("\n");
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
String result=sb.toString();
for(int i=0;i<loop;i++) {
Item sparepart = new Item(result, result);
itemlist.add(sparepart);
}
PersonListAdapter adapter = new PersonListAdapter(this, R.layout.adapter_view_layout,itemlist);
mListView.setAdapter(adapter);
String number = intent.getStringExtra(MainActivity2.extraint);
if(number != null) {
FrameLayout lay = (FrameLayout) findViewById(R.id.frames);
if (number.equals("1")) {
lay.setVisibility(View.INVISIBLE);
mListView.setVisibility(View.VISIBLE);
} else {
}
}
else{}
}
public void onBtnClick (View view){
Intent intent = new Intent(this,MainActivity2.class);
startActivity(intent);
}
}
The apps supposed to save one item by item into the internal storage which where i try to utilize array to save the into the internal storage, but it it possible to save and read array to internal storage?
I am trying to build an app for class and am having trouble with handling data that is gathered in another thread. The data does not seems to being passed through the handlers handleMessage method.
This is my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
ArrayList<Book> names;
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
// Handler bookHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
names = new ArrayList<Book>();
final EditText searchBar = findViewById(R.id.searchbar);
final Handler bookHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
String response = (String) msg.obj;
try{
JSONArray tmp = new JSONArray(response);
for(int i = 0; i < tmp.length(); i++){
JSONObject a = tmp.getJSONObject(i);
int id = a.getInt("book_id");
String title = a.getString("title");
Log.d("BOOK_id", a.getInt("book_id")+"");
String author = a.getString("author");
int published = a.getInt("published");
String coverUrl = a.getString("cover_url");
Book book = new Book(id,title,author,published,coverUrl);
names.add(book);
}
} catch (Exception e){
Log.d("FAIL", e.toString());
}
return false;
}
});
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
Log.d("Handler", response);
Message msg = Message.obtain();
msg.obj = response;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.e("Fail", e.toString());
}
}
};
t.start();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
JSONArray bookOBJ= new JSONArray(response);
Message msg = Message.obtain();
msg.obj = bookOBJ;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.d("Fail", e.toString());
}
}
};
t.start();
}
});
}
The code is suppose to get data from an api and then in the handleMessage method it is suppose to parse the data into a book object that contains two int and three string variables. The problem is that the handler never executes any code.
The execution should be that the debugger log should have the response string with the data from the API and then the id of every book in the JSON file, but it only has the data from the api displayed.
I am following this tutorial (http://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/)and try to implement rss feed reader
It working properly when I use
String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
instead of using
String RSSFEEDURL = "http://www.livescience.com/home/feed/health.xml";
This is my splash activity
package com.healthyhub.nadeesha.rsssave;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import com.healthyhub.nadeesha.rsssave.parser.DOMParser;
import com.healthyhub.nadeesha.rsssave.parser.RSSFeed;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SplashActivity extends Activity {
String RSSFEEDURL = "http://www.livescience.com/home/feed/health.xml";
// String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
RSSFeed feed;
String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}
Here is my DOMParser.java
package com.healthyhub.nadeesha.rsssave.parser;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// _feed.clearList();
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
/*newly added*/
/*here it returns NullPointer exception for theString*/
System.out.println( nchild.item(j).getFirstChild().getNodeValue());
/*end*/
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
} else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
} else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
e.printStackTrace();
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
Below part of the above code gives null pointer exception
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
/*newly added*/
/*here it returns NullPointer exception for theString*/
System.out.println( nchild.item(j).getFirstChild().getNodeValue());
/*end*/
This is my DetailFragment.java
package com.healthyhub.nadeesha.rsssave;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.healthyhub.nadeesha.rsssave.parser.RSSFeed;
public class DetailFragment extends Fragment {
private int fPos;
RSSFeed fFeed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fFeed = (RSSFeed) getArguments().getSerializable("feed");
fPos = getArguments().getInt("pos");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.detail_fragment, container, false);
// Initializr views
TextView title = (TextView) view.findViewById(R.id.title);
WebView desc = (WebView) view.findViewById(R.id.desc);
// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);
// Set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setLightTouchEnabled(false);
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);
// Set the views
title.setText(fFeed.getItem(fPos).getTitle());
desc.loadDataWithBaseURL("http://www.livescience.com/health/", fFeed
.getItem(fPos).getDescription(), "text/html", "UTF-8", null);
return view;
}
}
Simply what the above code does is
DOM Parser to Parse the XML data.
method returns the feed(RSSFeed) object:
Splash Activity we now call the method parseXml(String xml) from the DOMParser class
feed has been obtained in the onPostExecute() method we need to start the ListActivity and pass it the feed we
got, we do that by bundling the feed object and attaching it to the Intent
currently I am developing an Android Application (Native). In my application, I need to load many images and that cause a problem.
The problem is:
1. When I first open the app after deploy it on my android phone, it works fine. However, after I close the application (by clicking the back button), and then I open the application again, the app closed unexpectedly. When I check the logcat, I found out that it was closed because of OutOfMemory error.
2. Second problem: after I open my application, and I go to the next page, it also give me OutOfMemory error.
I guess, the problem occur because I load too many images. After I do some searching on the internet, it suggest me to do System.gc
But unfortunately, it did not work for me.
Here is my code:
Homepage_Activity.java
package dev.com.friseur;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.friseur.insert.AddComment;
import dev.friseur.rest.Photo;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class HomePage extends ActionBarActivity {
private String p_id = "1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Intent intent = getIntent();
int size = Integer.parseInt(intent.getStringExtra("size")) * 2;
LinearLayout hp = (LinearLayout)findViewById(R.id.homepage);
Photo photo = new Photo(hp, this, size);
photo.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, 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);
}
}
The photo.execute() code will call an asynchronous task. Here it is:
package dev.friseur.rest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.com.friseur.RecognizeFace;
import dev.com.friseur.ViewPhoto;
import dev.friseur.insert.AddComment;
import dev.friseur.insert.AddLike;
import android.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.SystemClock;
import android.text.InputFilter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Photo extends AsyncTask<String, Void, String>{
private Context context;
private LinearLayout homepage;
private int size;
private String sessionUname;
private String sessionUserid;
private File file;
private ArrayList<String> photo_id;
private ArrayList<String> imageName;
private ArrayList<String> date_upload;
private ArrayList<String> url_original;
private ArrayList<String> url_with_hair;
private ArrayList<String> caption;
private ArrayList<String> user_id;
private ArrayList<String> username;
private ArrayList<JSONArray> comments;
private ArrayList<Integer> totalcomment;
public Photo(LinearLayout homepage, Context context, int size){
this.context = context;
this.homepage = homepage;
this.size = size;
this.sessionUname = "testuser";
this.sessionUserid = "1";
photo_id = new ArrayList<String>();
imageName = new ArrayList<String>();
date_upload = new ArrayList<String>();
url_original = new ArrayList<String>();
url_with_hair = new ArrayList<String>();
caption = new ArrayList<String>();
user_id = new ArrayList<String>();
username = new ArrayList<String>();
comments = new ArrayList<JSONArray>();
totalcomment = new ArrayList<Integer>();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.43.8:8080/FriseurRest/WebService/GetPhotos");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
JSONObject json_data = new JSONObject(line);
photo_id.add(json_data.getString("p_id"));
imageName.add(json_data.getString("imagename"));
date_upload.add(json_data.getString("date_upload"));
url_original.add(json_data.getString("url_original"));
url_with_hair.add(json_data.getString("url_with_hair"));
caption.add(json_data.getString("caption"));
user_id.add(Integer.toString(json_data.getInt("user_id")));
username.add(json_data.getString("username"));
comments.add(json_data.getJSONArray("photoComments"));
totalcomment.add(json_data.getInt("total_comment"));
i++;
}
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onDestroy() {
System.gc();
Runtime.getRuntime().gc();
}
protected void onPostExecute(String p_id) {
for(int i = 0; i < imageName.size(); i++){
final int j = i;
LinearLayout photo = new LinearLayout(context);
photo.setOrientation(LinearLayout.VERTICAL);
photo.setPadding(0, 0, 0, 50);
LinearLayout postdesc = createPostDesc(i);
file = new File(Environment.getExternalStorageDirectory() + "/" + url_original.get(i), imageName.get(i));
Uri imgUri = Uri.fromFile(file);
ImageView img = new ImageView(context);
img.setImageURI(imgUri);
img.setMaxWidth(size);
img.setMinimumWidth(size);
img.setMaxHeight(size);
img.setMinimumHeight(size);
TextView tv = new TextView(context);
tv.setText(caption.get(i));
final LinearLayout showcomment = new LinearLayout(context);
showcomment.setOrientation(LinearLayout.VERTICAL);
showcomment.setPadding(0, 10, 0, 10);
try {
if(totalcomment.get(i) > 5){
LinearLayout more = new LinearLayout(context);
more.setPadding(0, 0, 0, 5);
TextView viewmore = new TextView(context);
viewmore.setTextColor(Color.GRAY);
viewmore.setText("View More Comments");
viewmore.setClickable(true);
viewmore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ViewPhoto.class);
intent.putExtra("size", size);
intent.putExtra("p_id", photo_id.get(j));
intent.putExtra("imageName", imageName.get(j));
intent.putExtra("date_upload", date_upload.get(j));
intent.putExtra("url_original", url_original.get(j));
intent.putExtra("url_with_hair", url_with_hair.get(j));
intent.putExtra("caption", caption.get(j));
intent.putExtra("user_id", user_id.get(j));
intent.putExtra("username", username.get(j));
context.startActivity(intent);
}
});
more.addView(viewmore);
showcomment.addView(more);
}
for(int k = 0; k < comments.get(i).length(); k++) {
//ArrayList<String> photoCom = comments.get(k);
//int userCom = photoCom.length();
JSONObject photoCom = comments.get(i).getJSONObject(k);
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(photoCom.getString("com_username"));
TextView showcom = new TextView(context);
showcom.setText(photoCom.getString("com_desc"));
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
} catch (Exception e) {
}
LinearLayout addcomment = createAddComment(i);
final EditText et_comment = new EditText(context);
et_comment.setHint("Add Comment");
et_comment.setMaxWidth(size*3/4);
et_comment.setMinimumWidth(size*3/4);
int maxLength = 150;
et_comment.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Button button_comment = new Button(context);
button_comment.setText("Post");
button_comment.setTextSize(15);
button_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String com = et_comment.getText().toString();
try{
AddComment ac = new AddComment(sessionUserid, com, photo_id.get(j));
ac.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(sessionUname);
TextView showcom = new TextView(context);
showcom.setText(com);
showcom.setAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in));
et_comment.setText("");
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
});
addcomment.addView(et_comment);
addcomment.addView(button_comment);
addcomment.setVisibility(View.GONE);
LinearLayout social = createSocialFeature(i, addcomment, et_comment);
photo.addView(postdesc);
photo.addView(img);
photo.addView(tv);
photo.addView(showcomment);
photo.addView(social);
photo.addView(addcomment);
homepage.addView(photo);
}
}
private LinearLayout createPostDesc(int i){
LinearLayout postdesc = new LinearLayout(context);
postdesc.setOrientation(LinearLayout.VERTICAL);
postdesc.setMinimumHeight(40);
TextView uname = new TextView(context);
uname.setText("#"+username.get(i));
TextView timeupload = new TextView(context);
timeupload.setText(date_upload.get(i));
if(i>0){
View separator = new View(context);
separator.setMinimumHeight(1);
separator.setBackgroundColor(Color.BLACK);
separator.setPadding(0, 10, 0, 0);
postdesc.addView(separator);
}
postdesc.addView(uname);
postdesc.addView(timeupload);
return postdesc;
}
private LinearLayout createSocialFeature(final int i, final LinearLayout addcomment, final EditText et_comment){
LinearLayout social = new LinearLayout(context);
social.setOrientation(LinearLayout.HORIZONTAL);
social.setMinimumHeight(40);
social.setPadding(0,10,10,0);
TextView tv_comment = new TextView(context);
tv_comment.setText("Add Comment");
tv_comment.setPadding(0, 0, 15, 0);
tv_comment.setClickable(true);
tv_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addcomment.setVisibility(View.VISIBLE);
et_comment.setFocusableInTouchMode(true);
et_comment.setFocusable(true);
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
});
final TextView tv_like = new TextView(context);
tv_like.setText("Like");
tv_like.setClickable(true);
tv_like.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String like = tv_like.getText().toString();
try{
AddLike lk = new AddLike(sessionUserid, like, photo_id.get(i));
lk.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(like.equals("Like")){
tv_like.setText("Unlike");
}
else{
tv_like.setText("Like");
}
}
});
social.addView(tv_comment);
social.addView(tv_like);
return social;
}
private LinearLayout createAddComment(int i){
LinearLayout addcomment = new LinearLayout(context);
addcomment.setId(Integer.parseInt(photo_id.get(i)));
addcomment.setOrientation(LinearLayout.HORIZONTAL);
addcomment.setPadding(0,20,0,0);
return addcomment;
}
}
This asynchronous task used to call the rest service.
What is wrong with my code? And how can I solve the OutOfMemory error. Any help would be appreciated. Thanks in advance
You can use lazyloading to fix this and follow this url for lazy loading:
https://github.com/nostra13/Android-Universal-Image-Loader
You can see my answer here.It will be useful to handle your bitmap efficiently.
How to make application more responsive which uses several bitmaps?
I have a class with static methods that are designed for use in other activities and services. These methods must show Toasts and update objects for any activities.
package com.app.myapp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class Wall {
private static final String TAG_Send_Error = "Send_error";
static String res;
public Wall() {
}
public static void Post(final String owner_id, final String message,
final String access_token) {
res = "";
new Thread(new Runnable() {
#Override
public void run() {
//
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("owner_id", owner_id));
params.add(new BasicNameValuePair("message", message
+ Constants.addtext));
params.add(new BasicNameValuePair("v", Constants.API_VERSION));
params.add(new BasicNameValuePair("access_token", access_token));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, "UTF-8");
Log.d("send", "start message sending");
HttpPost request = new HttpPost(Constants.API_URI
+ "wall.post");
request.setEntity(entity);//
Log.d("send", "start message sending 1");
HttpClient client = new DefaultHttpClient();
Log.d("send", "start message sending 2");
HttpResponse response = null;
response = client.execute(request);
Log.d("send", "start message sending 3");
HttpEntity entry = response.getEntity();
Log.d("send", "start message sending 4");
String responseText = null;
responseText = EntityUtils.toString(entry);
Log.d("send", responseText.toString());
JSONObject json = null;
json = new JSONObject(responseText);
if (json.has("error")) {
json = json.getJSONObject("error");
int err = json.getInt("error_code");
switch (err) {
case 0 - 15:
res = json.getString("error_msg");
break;
case 16:
break;
case 17:
break;
case 100:
res = "Invalid number of papams";
break;
}
} else {
res = "OK";
}
} catch (JSONException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (UnsupportedEncodingException e1) {
Log.e(TAG_Send_Error, e1.toString());
} catch (ClientProtocolException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (IOException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (ParseException e) {
Log.e(TAG_Send_Error, e.toString());
}
// Toast.makeText(context, res, 3).show();
// return res;
}
});
}
}
The Activity class:
package com.app.myapp;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class SendTestActivity extends Activity implements OnClickListener {
private EditText id_edit, txtedit;
private RadioButton sms_btn, wall_btn;
private Button sendbtn;
SharedPreferences prf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_test);
prf = PreferenceManager.getDefaultSharedPreferences(this);
id_edit = (EditText) findViewById(R.id.Send_a_id);
txtedit = (EditText) findViewById(R.id.Send_A_text);
sms_btn = (RadioButton) findViewById(R.id.Send_A_sms);
wall_btn = (RadioButton) findViewById(R.id.Send_A_wall);
sendbtn = (Button) findViewById(R.id.Send_A_sendbtn);
sendbtn.setOnClickListener(this);
prf = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Send_A_sendbtn:
if (sms_btn.isChecked()) {
}
if (wall_btn.isChecked()) {
Log.d("MY", "Отправка записи на стену");
Wall.Post(getApplicationContext(),
id_edit.getText().toString(), txtedit.getText()
.toString(), prf.getString("access_token", ""));
}
txtedit.setText("");
//Toast.makeText(getApplicationContext(), "ok", 3)
//.show();
break;
case R.id.Send_A_sms:
break;
case R.id.Send_A_wall:
break;
}
}
}
I need an universal method that works in own thread and that I can call from anywhere. This method must be able to change objects on the activity that call it and show toasts.
How I can solve my problem? ASyncTask?
Julia Hexen, your solution has not results, application also crash.
I had solved my problem. Before create a new thread I was created Handler:
final Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// здесь все обращения к интерфейсу
Toast.makeText(context, res, 3).show();
}
};
Finally, in the end of the code of a new thread I call method:
handler.sendEmptyMessage(0);