parsing xml asynctask and writing in listview - java
i want to parse my xml in asynctask because it won´t work without asynctask on android 4.0 +.The problem is that i cant write my strings in listview on my asynctask.
Here is my xml parsing activity:
package de.heron.cloudbox;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
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;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidXMLParsingActivity extends ListActivity{
String dwnload_file_path = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
String dest_file_path = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
Button b1;
ProgressDialog dialog = null;
///storage/emulated/0/everhomeapp.xml
// All static variables
static final String URL = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
//file:///storage/emulated/0/everhomeapp.xml
// XML node keys
static final String KEY_ITEM = "device"; // parent node
static final String KEY_ID = "deviceid";
static final String KEY_NAME = "devicename";
static final String KEY_actionid = "actions";
static final String KEY_actionid2 = "actions2";
static final String KEY_DESC = "devicetype";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
ArrayList<String> mImageLink;
String[] actions = new String[] {
"Alle Räume",
"Wohnzimmer",
"Küche",
"Gäste-Wc"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
overridePendingTransition( R.anim.leftright, R.anim.rightleft );
setTitle("Geräte");
getActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
// Adding menuItems to ListView
ListAdapter adapter2 = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter2);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String cost2 = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_actionid, cost);
in.putExtra(KEY_actionid2, cost2);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
try {
URL url = new URL("http://h.t-softec.de/heron.website.app/android/everhomeapp.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"everhomeapp.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
parseFile();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
parseFile();
} catch (IOException e) {
e.printStackTrace();
parseFile();
}
}
public void parseFile(){
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_actionid, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
}
public void parsexmllocal(){
mImageLink = new ArrayList<String>();
try{
File file = new File("mnt/sdcard/kursywalut.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("image");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
mImageLink.add(fstElmnt.getAttribute("link"));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
public void clicksound(View view){
MediaPlayer mp = MediaPlayer.create(this, R.raw.clicksound);
mp.start();
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.refresh:
try {
URL url = new URL("http://h.t-softec.de/heron.website.app/android/everhomeapp.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"everhomeapp.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
Toast.makeText(this, "Geräteliste erfolgreich aktualisiert!", Toast.LENGTH_LONG).show();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Handler handler4 = new Handler();
handler4.postDelayed(new Runnable()
{
#Override
public void run()
{
parseFile();
}
}, 100);
break;
case R.id.change:
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
break;
case android.R.id.home:
Intent i2 = new Intent(this, AndroidXMLParsingActivity2.class);
startActivity(i2);
break;
}
return true;
}
}
and here is my singlemenuitemactivity:
package de.heron.cloudbox;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
EditText txtCode;
// XML node keys
static final String KEY_NAME = "name";
static final String KEY_actionid = "cost";
static final String KEY_actionid2 = "cost2";
static final String KEY_DESC = "description";
static final String KEY_ID = "deviceid";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cost = in.getStringExtra(KEY_actionid);
String cost2 = in.getStringExtra(KEY_actionid2);
String description = in.getStringExtra(KEY_DESC);
String deviceid = in.getStringExtra(KEY_ID);
String on = in.getStringExtra(KEY_texton);
String off = in.getStringExtra(KEY_textoff);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
TextView lblid = (TextView) findViewById(R.id.id_label);
// TextView lblon = (Button) findViewById(R.id.on);
// TextView lbloff = (Button) findViewById(R.id.off);
Button lblon = (Button)findViewById(R.id.on);
lblon.getText().toString();
lblon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
txtCode.setText(settings.getString("Code", "").toString());
String[] url={"http://everhome.de/api/applive/", (settings.getString("Code", "")), "/" + KEY_ID,"/" + KEY_actionid};
new onoff(SingleMenuItemActivity.this).execute(url);
}});
Button lbloff = (Button)findViewById(R.id.off);
lbloff.getText().toString();
lbloff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] url={"http://everhome.de/api/applive/", "8ef43502ad3dc04f87b4a48b993878c0","/" + KEY_ID,"/" + KEY_actionid2};
new onoff(SingleMenuItemActivity.this).execute(url);
}
});
lblName.setText(name);
lblCost.setText(cost);
lblCost.setText(cost2);
lblDesc.setText(description);
lblid.setText(deviceid);
lblon.setText(on);
lbloff.setText(off);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setIcon(R.drawable.ic_launcher);
setTitle("Geräte");
Button devices = (Button) findViewById(R.id.devices);
devices.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(SingleMenuItemActivity.this, AndroidXMLParsingActivity.class);
startActivity(i);
}
});
Button scenes = (Button) findViewById(R.id.scenes);
scenes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(SingleMenuItemActivity.this, AndroidXMLParsingActivity2.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.refresh:
break;
}
return true;
}
}
i hope anybody can help me to resolve my problem.
Update:
thats was the test with asynctask:
class xmlparse extends AsyncTask<Void, Void, Void> {
static final String KEY_ITEM = "device"; // parent node
static final String KEY_ID = "deviceid";
static final String KEY_NAME = "devicename";
static final String KEY_actionid = "actions";
static final String KEY_actionid2 = "actions2";
static final String KEY_DESC = "devicetype";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
#Override
protected Void doInBackground(Void... params) {
/*
make connection & download XML here,
use your XML parser class object to parse the xml from here
create ArrayList & etc. from here...
*/
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//
//File xml = parser.getXmlFromUrl(URL); // getting XML
//Document doc = parser.getDomElement(xml); // getting DOM element
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
// adding HashList to ArrayList
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// postexecute logic
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// pre execute logic
super.onPreExecute();
}
}
but the problem is that i want to put the strings(menu items ) in listview with the listadapter:
ListAdapter adapter2 = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter2);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String cost2 = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
and i dont know how i can make this when the parser runs in asynctask.
that make the parser to put the menuitems to the listadapter:
menuItems.add(map);
Reference your adapter through a WeakReference when initializing your Asynctask.
Parametrize the AsyncTask to return whatever you need to return, e.g. a List<String>. The connection and data pulling happens in doInBackground.
In onPostExecute, check your WeakReference.get is not null and populate the adapter.
You can use the droidQuery library to asynchronously download an XML Document given a URL. For example:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("GET")
.context(this)
.dataType("xml")
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
Document xml = (Document) params[0];
//TODO parse xml here. This is the UI Thread, so you can also modify your TextViews here.
}
})
.error(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
AjaxError e = (AjaxError) params[0];
droidQuery.alert("Error: " + e.status + ": " + e.error);
}
}));
Related
Interface returning null after doing search
RecyclerView is updated after the search and mCallback returns null but before search works correctly. AdapterHistorico.java package com.beliasdev.cadjobel.adapter; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.beliasdev.cadjobel.R; import com.beliasdev.cadjobel.utility.DrawableHelper; import com.bumptech.glide.Glide; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Spinner spinner1; private String dateold; private String datenew; private String compareValue; private String concluido; private String em_andamento; private String cancelado; private String concluido1; private String em_andamento1; private String cancelado1; private String status; private Context context; private LayoutInflater inflater; private IProcessFilter mCallback; private ArrayList<DataHistorico> data; //List<DataHistorico> data= Collections.emptyList(); DataHistorico current; int currentPos=0; public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){ this.context=context; inflater= LayoutInflater.from(context); this.data=data; mCallback = callback; } public interface IProcessFilter { void onProcessFilter(DataHistorico produtos); } #Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view=inflater.inflate(R.layout.container_historico, parent,false); MyHolder holder=new MyHolder(view); return holder; } #Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final DataHistorico pedidos = data.get(position); values from list MyHolder myHolder= (MyHolder) holder; final DataHistorico current = data.get(position); dateold = current.pData; try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss"); datenew = df2.format(format.parse(dateold)); } catch (ParseException e) { e.printStackTrace(); } myHolder.txtPedidoNumero.setText("N° " + current.pNumero); myHolder.txtPedidoCliente.setText(current.pCliente); myHolder.txtPedidoData.setText(datenew); myHolder.txtPedidoTotal.setText("R$ " + current.pTotal); myHolder.edtPedido.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { mCallback.onProcessFilter(pedidos); //NullPointerException here } }); // load image into imageview using glide concluido = "concluido"; cancelado = "cancelado"; em_andamento= "em_andamento"; status = current.pStatus; if (status.equals(concluido)) { Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus); } else if (status.equals(cancelado)) { Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus); }else if (status.equals(em_andamento)) { Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus); } } // return total item from List #Override public int getItemCount() { return data.size(); } class MyHolder extends RecyclerView.ViewHolder{ TextView txtPedidoNumero; TextView txtPedidoCliente; ImageView imgPedidoStatus; TextView txtPedidoData; TextView txtPedidoTotal; ImageView edtPedido; // create constructor to get widget reference public MyHolder(View itemView) { super(itemView); txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero); txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente); imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus); txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData); txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal); edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido); } } } FragmentoHistorico.java public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter { [...] public void onProcessFilter(DataHistorico pedidos) { EditarPedidoDialog(pedidos); } private void EditarPedidoDialog(final DataHistorico pedidos){ LayoutInflater inflater = LayoutInflater.from(getActivity()); final View subView = inflater.inflate(R.layout.layout_edt_pedido, null); [...] private class ProcurarPedido extends AsyncTask<String, String, String> { ProgressDialog pdLoading = new ProgressDialog(getActivity()); HttpURLConnection conn; URL url = null; private String searchQuery; private View rootView; public ProcurarPedido(String searchQuery, View rootView){ this.searchQuery=searchQuery; this.rootView=rootView; } #Override protected void onPreExecute() { super.onPreExecute(); //this method will be running on UI thread pdLoading.setMessage("\tAguarde..."); pdLoading.setCancelable(false); pdLoading.show(); } #Override protected String doInBackground(String... params) { try { // Enter URL address where your php file resides url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return e.toString(); } try { // Setup HttpURLConnection class to send and receive data from php and mysql conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(READ_TIMEOUT); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.setRequestMethod("POST"); // setDoInput and setDoOutput to true as we send and recieve data conn.setDoInput(true); conn.setDoOutput(true); // add parameter to our above url Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery); String query = builder.build().getEncodedQuery(); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conn.connect(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return e1.toString(); } try { int response_code = conn.getResponseCode(); // Check if successful connection made if (response_code == HttpURLConnection.HTTP_OK) { // Read data sent from server InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // Pass data to onPostExecute method return (result.toString()); } else { return("Erro na conexão!"); } } catch (IOException e) { e.printStackTrace(); return e.toString(); } finally { conn.disconnect(); } } #Override protected void onPostExecute(String result) { //this method will be running on UI thread Log.v("result", result); pdLoading.dismiss(); ArrayList<DataHistorico> data=new ArrayList<>(); if(result.equals("no rows")) { mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo); mAdapter = new AdapterHistorico(getActivity(), data, null); mRVHistoricoInfo.setAdapter(mAdapter); mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity())); data.clear(); Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show(); }else{ try { data.clear(); JSONArray jArray = new JSONArray(result); // Extract data from json and store into ArrayList as class objects for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); DataHistorico historicoData = new DataHistorico(); historicoData.pNumero= json_data.getString("nid"); historicoData.pStatus= json_data.getString("pedido_status"); historicoData.pCliente= json_data.getString("pedido_cliente"); historicoData.pEndereco= json_data.getString("pedido_endereco"); historicoData.pData= json_data.getString("pedido_data"); historicoData.pTotal= json_data.getString("pedido_total"); data.add(historicoData); } mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo); mAdapter = new AdapterHistorico(getActivity(), data, null); mRVHistoricoInfo.setAdapter(mAdapter); mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity())); } catch (JSONException e) { // You to understand what actually error is and handle it appropriately Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show(); } } } } [...] This is the error: java.lang.NullPointerException: Attempt to invoke interface method 'void com.beliasdev.cadjobel.adapter.AdapterHistorico$IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)' on a null object reference
You are sending null instead of listener as a parameter: So change mAdapter = new AdapterHistorico(getActivity(), data, null); To mAdapter = new AdapterHistorico(getActivity(), data, this);
Load more items and add bottom to the list when scroll down in android
I tried to implement for adding more items to my adapter but its refreshing every time instead of adding new items to bottom of the list.I searched through the internet but i didn't get the solution Here is my code: import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; public class MainActivity extends AppCompatActivity { private DataListAdapter dataListAdapter; Activity _activity; ArrayList<DataObject> dataArrayList; private ListView lv; private String jsonResult; boolean loadingMore = false; private DataObject dataObject; private static final String TAG = MainActivity.class.getSimpleName(); #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _activity = this; lv = (ListView) findViewById(R.id.listView1); View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false); this.lv.addFooterView(footerView); if (isOnline(_activity)) { new LoadJsonData().execute(); scrollNotifyChange(); } } private void scrollNotifyChange() { lv.setOnScrollListener(new AbsListView.OnScrollListener() { #Override public void onScrollStateChanged(AbsListView view, int scrollState) { } #Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { //what is the bottom item that is visible int lastInScreen = firstVisibleItem + visibleItemCount; //is the bottom item visible & not loading more already? Load more! if ((lastInScreen == totalItemCount) && !(loadingMore)) { // //start a new thread for loading the items in the list Thread thread = new Thread(null, loadMoreListItems); thread.start(); } } }); } private Runnable loadMoreListItems = new Runnable() { #Override public void run() { //Set flag so we cant load new items 2 at the same time loadingMore = true; //Reset the array that holds the new items //Simulate a delay, delete this on a production environment! try { Thread.sleep(1000); } catch (InterruptedException e) { } jsonResult = doInBackground(); runOnUiThread(returnRes); } }; private Runnable returnRes = new Runnable() { #Override public void run() { onPostExecute(jsonResult); loadingMore = false; } }; public String doInBackground() { String jsonResult = ""; // jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php"); // return jsonResult; InputStream inputStream = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php"); HttpResponse httpResponse = httpclient.execute(request); inputStream = httpResponse.getEntity().getContent(); if (inputStream != null) { jsonResult = convertInputStreamToString(inputStream); } else { jsonResult = "Did not work!"; } } catch (Exception e) { Log.e(TAG, "GET failed", e); } return jsonResult; } public void onPostExecute(String result) { try { // progress.dismiss(); dataArrayList = new ArrayList<DataObject>(); JSONObject dataJsontObject = new JSONObject(result); JSONArray dataJsonArray = dataJsontObject.getJSONArray("data"); for (int i = 0; i < dataJsonArray.length(); i++) { JSONArray dataSubArray = dataJsonArray.getJSONArray(i); dataObject = new DataObject(); dataObject.setName((String) dataSubArray.get(0)); dataObject.setType((String) dataSubArray.get(1)); dataObject.setProfession((String) dataSubArray.get(2)); dataObject.setCountry((String) dataSubArray.get(3)); dataObject.setCurrency((String) dataSubArray.get(5)); dataArrayList.add(dataObject); } dataListAdapter = new DataListAdapter(dataArrayList); dataListAdapter.add(dataObject); // lv.setAdapter(dataListAdapter); // dataListAdapter.add(dataObject); dataListAdapter.notifyDataSetChanged(); lv.setAdapter(dataListAdapter); lv.smoothScrollToPosition(dataListAdapter.getCount()); } catch (JSONException e) { e.printStackTrace(); } } public static boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } private class LoadJsonData extends AsyncTask<Void, Void, String> { ProgressDialog progress; #Override protected void onPreExecute() { super.onPreExecute(); progress = ProgressDialog.show(_activity, "Progress", "Please wait", true); } #Override protected String doInBackground(Void... params) { String jsonResult = ""; // jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php"); // return jsonResult; InputStream inputStream = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php"); HttpResponse httpResponse = httpclient.execute(request); inputStream = httpResponse.getEntity().getContent(); if (inputStream != null) { jsonResult = convertInputStreamToString(inputStream); } else { jsonResult = "Did not work!"; } } catch (Exception e) { Log.e(TAG, "GET failed", e); } return jsonResult; } #Override protected void onPostExecute(String result) { super.onPostExecute(result); try { progress.dismiss(); if(loadingMore) { // listViwe.removeFooterView(loadingFooter); loadingMore = false; } dataArrayList = new ArrayList<DataObject>(); JSONObject dataJsontObject = new JSONObject(result); JSONArray dataJsonArray = dataJsontObject.getJSONArray("data"); for (int i = 0; i < dataJsonArray.length(); i++) { JSONArray dataSubArray = dataJsonArray.getJSONArray(i); DataObject dataObject = new DataObject(); dataObject.setName((String) dataSubArray.get(0)); dataObject.setType((String) dataSubArray.get(1)); dataObject.setProfession((String) dataSubArray.get(2)); dataObject.setCountry((String) dataSubArray.get(3)); dataObject.setCurrency((String) dataSubArray.get(5)); dataArrayList.add(dataObject); } dataListAdapter = new DataListAdapter(dataArrayList); lv.setAdapter(dataListAdapter); dataListAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); if(loadingMore) { // listViwe.removeFooterView(loadingFooter); loadingMore = false; } } } } public class DataListAdapter extends BaseAdapter { ArrayList<DataObject> dataListObject = new ArrayList<DataObject>(); public DataListAdapter(ArrayList<DataObject> dataListObject) { this.dataListObject = dataListObject; } #Override public int getCount() { return dataListObject.size(); } #Override public Object getItem(int position) { return dataListObject.get(position); } #Override public long getItemId(int position) { return position; } public void add(DataObject dataObject){ // Log.v("AddView", country.getCode()); this.dataListObject.add(dataObject); } #Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(_activity); convertView = inflater.inflate(R.layout.single_row, null); holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.name); holder.type = (TextView) convertView.findViewById(R.id.type); holder.profession = (TextView) convertView.findViewById(R.id.profession); holder.country = (TextView) convertView.findViewById(R.id.country); holder.currency = (TextView) convertView.findViewById(R.id.currecy); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final DataObject current = dataListObject.get(position); holder.name.setText("Name--" + current.getName()); holder.type.setText("Type--" + current.getType()); holder.profession.setText("Professoion--" + current.getProfession()); holder.country.setText("Country--" + current.getCountry()); holder.currency.setText("Currency--" + current.getCurrency()); return convertView; } } static class ViewHolder { TextView name; TextView type; TextView profession; TextView country; TextView currency; } public static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; String result = ""; while ((line = bufferedReader.readLine()) != null) { result += line; } inputStream.close(); return result; } }
you need to create an adapter inside onCreate method like this: ArrayList<DataObject> list; onCreate() { list=new ArrayList(); ListAdapter dataListAdapter =new ListAdapter(list) // creating an adapter with empty list of data listView.setAdpater(adpater); } then, in onPostExceute() method : add data to the ArrayList and notifythe adapter like this: onPostExecute(){ .... ..... list.add(dataObject); //here you can add 'n' number of object to the list dataListAdapter.notifyDataSetChanged(); // notify the adapter to update the listview ..... } EDIT : I updated this answer as per #user3422948 request DataListAdapter dataListAdapter; ArrayList<DataObject> dataArrayList; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _activity = this; //edit: declare your arraylist and adapter here dataArrayList = new ArrayList<DataObject>(); dataListAdapter = new DataListAdapter(dataArrayList); lv = (ListView) findViewById(R.id.listView1); View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false); this.lv.addFooterView(footerView); if (isOnline(_activity)) { new LoadJsonData().execute(); scrollNotifyChange(); } } ...... ....... public void onPostExecute(String result) { try { // progress.dismiss(); //dataArrayList = new ArrayList<DataObject>(); //edit JSONObject dataJsontObject = new JSONObject(result); JSONArray dataJsonArray = dataJsontObject.getJSONArray("data"); for (int i = 0; i < dataJsonArray.length(); i++) { JSONArray dataSubArray = dataJsonArray.getJSONArray(i); dataObject = new DataObject(); dataObject.setName((String) dataSubArray.get(0)); dataObject.setType((String) dataSubArray.get(1)); dataObject.setProfession((String) dataSubArray.get(2)); dataObject.setCountry((String) dataSubArray.get(3)); dataObject.setCurrency((String) dataSubArray.get(5)); dataArrayList.add(dataObject); } //edit: your creating new adapter for every execution //dataListAdapter = new DataListAdapter(dataArrayList); //dataListAdapter.add(dataObject); // lv.setAdapter(dataListAdapter); // dataListAdapter.add(dataObject); dataListAdapter.notifyDataSetChanged(); //lv.setAdapter(dataListAdapter); lv.smoothScrollToPosition(dataListAdapter.getCount()); } catch (JSONException e) { e.printStackTrace(); } } the problem is for every execution you are creating new Adapter you should see this link how to use notifyDataSetChanged in listView
AsyncTask spawns a new intelligent thread on its own, runs things in background and also posts results of UI thread in onPostExecute method. You should not call the methods of AsyncTask on your own. Android does it by itself. Instead of calling a new thread in scrollchangelistener,like: Thread thread = new Thread(null, loadMoreListItems); call new LoadJsonData().execute(); you don't need two Runnable threads to do the same thing your asyncTask does. The problem is this code of yours: dataListAdapter = new DataListAdapter(dataArrayList); lv.setAdapter(dataListAdapter); Every time your scrolling reaches the end, it eventually calls the onPostExecute method to post results on the UI. But here you are making a new Adapter eveytime with a new dataset which is why it always refreshes the whole list. Remove this part and set it inside onCreate of your Activity.Add new values to your adapter's datalist in onPostExecute. Then just do a notifyDataSetChanged inside onPostExecute of your AsyncTask.
Rss Feeds reader gives blank screen for .xml link
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
Eclipse Java ADT errors
When I run this code: package com.example.topliga; public class Update extends AutomaticUpdaterActivity { private Object context; protected String doInBackground(String... sUrl) { String path = "http://192.168.1.20/android/TopLiga.apk"; try { URL url = new URL(sUrl[0]); URLConnection connection = url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(path); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) { Log.e("YourApp", "Well that didn't work out so well..."); Log.e("YourApp", e.getMessage()); } return path; } private void publishProgress(int i) { } #Override protected void onPostExecute(String path) { Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); i.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive" ); Log.d("Lofting", "About to install new .apk"); ((Activity) this.context).startActivity(i); } } import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; 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.example.updater.AutomaticUpdaterActivity; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.ListAdapter; import android.widget.SimpleAdapter; #SuppressLint("ParserError") public class TopLigaActivity extends ListActivity { static final String URL = "http://minesemhamachi.no-ip.org/android/usersdata.xml"; static final String KEY_ITEM = "mydata"; // nodo pai static final String KEY_ID = "id"; static final String KEY_username = "Username"; static final String KEY_password = "Password"; XMLParser parser; #SuppressLint({ "ParserError", "NewApi" }) #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { parser = new XMLParser(); new DownloadXml().execute(URL); } } private void setListView(String xml) { ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); // Obter elemento (DOM) Document doc = parser.getDomElement(xml); NodeList nl = doc.getElementsByTagName(KEY_ITEM); // Iteração sobre todos os nodos <item> for (int i = 0; i < nl.getLength(); i++) { // Criação de HashMap HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); // Adição de cada nodo filho ao HashMap key => value map.put(KEY_ID, parser.getValue(e, KEY_ID)); map.put(KEY_username, parser.getValue(e, KEY_username)); map.put(KEY_password, parser.getValue(e, KEY_password)); // adição da HashList ao ArrayList menuItems.add(map); } // Adição dos menuItems ao ListView ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item, new String[] { KEY_username, KEY_password }, new int[] { R.id.name, R.id.score }); setListAdapter(adapter); } private class DownloadXml extends AsyncTask<String, Integer, String> { #Override protected String doInBackground(String... urls) { return parser.getXmlFromUrl(urls[0]); } #Override protected void onPostExecute(String result) { setListView(result); } } } These errors happen: Syntax error on token(s), misplaced construct(s) TopLigaActivity.java /TopLiga/src/com/example/topliga line 3 Java Problem The public type Update must be defined in its own file TopLigaActivity.java /TopLiga/src/com/example/topliga line 3 Java Problem The objective of this code is to check if there is a newer version of this .apk app and, if there is, transfer the new one.
You code had a misplaced } in it that made the class finish to soon. This bracket was suposed to be at the very end of you code. So I moved it for you I also moved your imports to the top. And also TopLigaActivity is now a nested class inside Update. If you do not want this you should move it to it's own file so that there's a file named Update and a file named TopLigaActivity. You'll have to do this because you cannot difine two different classes in one file (unless it's a nested class). By the way the bracket I move was the one directly above your imports. Here is your 'new' code: import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; 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.example.updater.AutomaticUpdaterActivity; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.ListAdapter; import android.widget.SimpleAdapter; public class Update extends AutomaticUpdaterActivity { private Object context; protected String doInBackground(String... sUrl) { String path = "http://192.168.1.20/android/TopLiga.apk"; try { URL url = new URL(sUrl[0]); URLConnection connection = url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(path); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) { Log.e("YourApp", "Well that didn't work out so well..."); Log.e("YourApp", e.getMessage()); } return path; } private void publishProgress(int i) { } #Override protected void onPostExecute(String path) { Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); i.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive" ); Log.d("Lofting", "About to install new .apk"); ((Activity) this.context).startActivity(i); } #SuppressLint("ParserError") public class TopLigaActivity extends ListActivity { static final String URL = "http://minesemhamachi.no-ip.org/android/usersdata.xml"; static final String KEY_ITEM = "mydata"; // nodo pai static final String KEY_ID = "id"; static final String KEY_username = "Username"; static final String KEY_password = "Password"; XMLParser parser; #SuppressLint({ "ParserError", "NewApi" }) #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { parser = new XMLParser(); new DownloadXml().execute(URL); } } private void setListView(String xml) { ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); // Obter elemento (DOM) Document doc = parser.getDomElement(xml); NodeList nl = doc.getElementsByTagName(KEY_ITEM); // Iteração sobre todos os nodos <item> for (int i = 0; i < nl.getLength(); i++) { // Criação de HashMap HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); // Adição de cada nodo filho ao HashMap key => value map.put(KEY_ID, parser.getValue(e, KEY_ID)); map.put(KEY_username, parser.getValue(e, KEY_username)); map.put(KEY_password, parser.getValue(e, KEY_password)); // adição da HashList ao ArrayList menuItems.add(map); } // Adição dos menuItems ao ListView ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item, new String[] { KEY_username, KEY_password }, new int[] { R.id.name, R.id.score }); setListAdapter(adapter); } private class DownloadXml extends AsyncTask<String, Integer, String> { #Override protected String doInBackground(String... urls) { return parser.getXmlFromUrl(urls[0]); } #Override protected void onPostExecute(String result) { setListView(result); } } } } I hope that this solves your problem. P.S. you could also make Update a subclass of TopLigaActivity.
Android - get XML from web
I'm trying to get XML datas from web and to show these datas into ListView. But something's going wrong when i run the project. Can you help me for this problem,please? Thank you. XMLParser.java public class XMLParser extends Activity { public String getXmlFromUrl(String url) { String xml = null; try { new Thread(new Runnable() { public void run() { try { URL uri=new URL("http://api.androidhive.info/pizza/?format=xml"); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); System.out.println("done"); } catch(Exception e) { e.printStackTrace(); } } }).start(); //readfilethread.start(); // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); System.out.println("here"); // HttpResponse httpResponse = httpClient.execute(httpPost); //HttpEntity httpEntity = httpResponse.getEntity(); //xml = EntityUtils.toString(httpEntity); } catch (Exception 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; } // 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 ""; } AndroidXMLParsingActivity.java public class AndroidXMLParsingActivity extends ListActivity { // All static variables.. static final String URL = "http://api.androidhive.info/pizza/?format=xml"; // XML node keys static final String KEY_ITEM = "item"; // parent node static final String KEY_ID = "id"; static final String KEY_NAME = "name"; static final String KEY_COST = "cost"; static final String KEY_DESC = "description"; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // -> menuItems ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // 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_ID, parser.getValue(e, KEY_ID)); map.put(KEY_NAME, parser.getValue(e, KEY_NAME)); map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST)); map.put(KEY_DESC, parser.getValue(e, KEY_DESC)); // adding HashList to ArrayList menuItems.add(map); } // 2. Adding menuItems to ListView ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item, new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] { R.id.name, R.id.description, R.id.cost }); setListAdapter(adapter); // selecting single ListView item android.widget.ListView lv = getListView(); // listening to single list item click lv.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString(); String description = ((TextView) view.findViewById(R.id.description)).getText().toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), SingleListItem.class); in.putExtra(KEY_NAME, name); in.putExtra(KEY_COST, cost); in.putExtra(KEY_DESC, description); startActivity(in); } }); } } ' LOGCAT PART 08-25 08:34:10.211: E/AndroidRuntime(1700): FATAL EXCEPTION: main 08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException 08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException 08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.access$600(ActivityThread.java:141) 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Handler.dispatchMessage(Handler.java:99) 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Looper.loop(Looper.java:137) 08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.main(ActivityThread.java:5039) .... 08-25 08:34:10.341: I/System.out(1700): done
Try this codes ... import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.annotation.TargetApi; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class NetActivity extends Activity { String url = "http://api.androidhive.info/pizza/?format=xml"; // Progress dialog ProgressDialog pDialog; ArrayList<String> title; ArrayList<String> description; ArrayList<String> id; ArrayList<String> cost; ItemAdapter adapter1; ListView list; #TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_net); list = (ListView) findViewById(R.id.list); title = new ArrayList<String>(); description = new ArrayList<String>(); id = new ArrayList<String>(); cost = new ArrayList<String>(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) new XmlParsing(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null}); else new XmlParsing(url).execute(new String[]{null}); } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public class XmlParsing extends AsyncTask<String, Void, String> { // variables passed in: String urls; // constructor public XmlParsing(String urls) { this.urls = urls; } #Override protected void onPreExecute() { pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true); } #Override protected String doInBackground(String... params) { // TODO Auto-generated method stub URL url; try { url = new URL(urls); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(url.openStream())); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("item"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("name"); Element nameElement = (Element) nameList.item(0); nameList = nameElement.getChildNodes(); title.add(""+ ((Node) nameList.item(0)).getNodeValue()); System.out.println("name : "+((Node) nameList.item(0)).getNodeValue()); Element fstElmnt1 = (Element) node; NodeList nameList1 = fstElmnt1.getElementsByTagName("id"); Element nameElement1 = (Element) nameList1.item(0); nameList1 = nameElement1.getChildNodes(); description.add(""+ ((Node) nameList1.item(0)).getNodeValue()); System.out.println("id : "+ ((Node) nameList1.item(0)).getNodeValue()); Element fstElmnt2 = (Element) node; NodeList nameList2 = fstElmnt2.getElementsByTagName("cost"); Element nameElement2 = (Element) nameList2.item(0); nameList2 = nameElement2.getChildNodes(); id.add(""+ ((Node) nameList2.item(0)).getNodeValue()); System.out.println("cost : "+ ((Node) nameList2.item(0)).getNodeValue()); Element fstElmnt3 = (Element) node; NodeList nameList3 = fstElmnt3.getElementsByTagName("description"); Element nameElement3 = (Element) nameList3.item(0); nameList3 = nameElement3.getChildNodes(); cost.add(""+ ((Node) nameList3.item(0)).getNodeValue()); System.out.println("description : "+ ((Node) nameList3.item(0)).getNodeValue()); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } #Override protected void onPostExecute(String result) { // Now we have your JSONObject, play around with it. if (pDialog.isShowing()) pDialog.dismiss(); adapter1 = new ItemAdapter(this); list.setAdapter(adapter1); } } class ItemAdapter extends BaseAdapter { final LayoutInflater mInflater; private class ViewHolder { public TextView title_text; public TextView des_text; public TextView id_text; public TextView cost_text; } public ItemAdapter(XmlParsing xmlParsing) { // TODO Auto-generated constructor stub super(); mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } //#Override public int getCount() { return title.size(); } //#Override public Object getItem(int position) { return position; } //#Override public long getItemId(int position) { return position; } //#Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; final ViewHolder holder; if (convertView == null) { view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false); holder = new ViewHolder(); holder.title_text = (TextView) view.findViewById(R.id.title_text); holder.des_text = (TextView) view.findViewById(R.id.des_text); holder.id_text = (TextView) view.findViewById(R.id.id_text); holder.cost_text = (TextView) view.findViewById(R.id.cost_text); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.title_text.setText(""+title.get(position)); holder.des_text.setText(""+description.get(position)); holder.id_text.setText(""+id.get(position)); holder.cost_text.setText(""+cost.get(position)); return view; } } }