I am parsing json but in my jsonarray I have another array and this arrays values have no tags.(property name.) Here is my code. I can parse the other values but not gallery array. How can I parse gallery array's values in onitemclick method? Thanks.
My json link: http://kilimmobilya.com.tr/mobileservices/default.aspx?i=yeniUrunler
My json:
{
"veri": [
{
"id": "1436",
"tarih": "08.10.2012",
"baslik": "Ares Plazma TV \u00dcnitesi",
"kImaj": "http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/210x120/Ares-Plazma-VS1-00.jpg",
"kisaAciklama": "",
"icerik": "",
"fiyat": "799",
"Gallery": [
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-01.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-02.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-01.jpg"
]
},
{
"id": "1434",
"tarih": "08.10.2012",
"baslik": "Ares Yatak Odas\u0131",
"kImaj": "http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/210x120/Ares-Yatak-Odasi-Takim-00.jpg",
"kisaAciklama": "",
"icerik": "",
"fiyat": "5690",
"Gallery": [
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-00-1.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-01.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-02.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-03.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-04.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-05.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-06.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-07.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-08.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-09.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-10.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-11.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-12.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-13.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-14.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-15.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-16.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-17.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-18.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-19.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-20.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-21.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-22.jpg"
]
}
package com.eticaret.hakan;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.eticaret.hakan.R;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Yeniurunler extends Activity implements OnItemClickListener,OnClickListener {
int gelencatid;
Button altkampanya,altkatalog,altbayi,altiletisim;
private static final String rssFeed = "http://kilimmobilya.com.tr/mobileservices/default.aspx?i=yeniUrunler";
private static final String link="http://salih.arti-sanat.com/e-ticaret/s3.jpg";
private static final String TAG_PRODUCTS = "veri";
private static final String TAG_PID = "id";
private static final String TAG_PNAME = "baslik";
private static final String TAG_PPRICE = "tarih";
private static final String TAG_PDESCRIPTION = "kisaAciklama";
private static final String TAG_CREATEDAT = "tarih";
private static final String TAG_LINK = "kImaj";
private static final String TAG_GALLERY="Gallery";
List<Item> arrayOfList;
ListView listView;
KampanyaRowAdapter objAdapter;
JSONArray jsonArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.yeniurunler);
altkampanya=(Button) findViewById(R.id.altkampanyalar);
altkatalog=(Button) findViewById(R.id.altkataloglar);
altbayi=(Button) findViewById(R.id.altbayilerimiz);
altiletisim=(Button) findViewById(R.id.altiletisim);
altkampanya.setOnClickListener(this);
altkatalog.setOnClickListener(this);
altbayi.setOnClickListener(this);
altiletisim.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
listView.setDivider(new ColorDrawable(0x90000000));
listView.setDividerHeight(1);
listView.setOnItemClickListener(this);
arrayOfList = new ArrayList<Item>();
if (Utils.isNetworkAvailable(Yeniurunler.this)) {
new MyTask().execute(rssFeed);
} else {
showToast("Ağ bağlantısı yok!!!");
}
}
// My AsyncTask start...
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Yeniurunler.this);
pDialog.setMessage("Yükleniyor...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Ürün Bulunamadı");
Yeniurunler.this.finish();
} else {
try {
JSONObject mainJson = new JSONObject(result);
jsonArray = mainJson.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
Item objItem = new Item();
objItem.setName(objJson.getString(TAG_PNAME));
objItem.setCity(objJson.getString(TAG_PDESCRIPTION));
objItem.setLink(objJson.getString(TAG_LINK));
//objItem.setLink(link);
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
// check data...
/*
* for (int i = 0; i < arrayOfList.size(); i++) { Item item =
* arrayOfList.get(i); System.out.println(item.getId());
*
* System.out.println(item.getId());
* System.out.println(item.getName());
* System.out.println(item.getCity());
* System.out.println(item.getGender());
* System.out.println(item.getAge());
* System.out.println(item.getBirthdate()); }
*/
Collections.sort(arrayOfList, new Comparator<Item>() {
public int compare(Item lhs, Item rhs) {
return (lhs.getAge() - rhs.getAge());
}
});
setAdapterToListview();
}
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent a = new Intent(getApplicationContext(), YeniUrunDetay.class);
// starting new activity and expecting some response back
startActivity(a);
// sending pid to next activity
}
public void setAdapterToListview() {
objAdapter = new KampanyaRowAdapter(Yeniurunler.this, R.layout.kampanyarow,
arrayOfList);
listView.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(Yeniurunler.this, msg, Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.altkampanyalar:
Intent goAltkampanya= new Intent(this, Kampanyalar.class);
startActivity(goAltkampanya);
break;
case R.id.altkataloglar:
Intent goAltkatalog = new Intent(this, Kataloglar.class);
startActivity(goAltkatalog);
break;
case R.id.altbayilerimiz:
Intent goBAyi= new Intent(this, Bayiler.class);
startActivity(goBAyi);
break;
case R.id.altiletisim:
Intent goAltiletisim= new Intent(this, Iletisim.class);
startActivity(goAltiletisim);
break;
}
}
}
This is your POJO
public class Veri {
private long id;
private String date;
private String baslik;
private String kImagj;
private String kisaAciklama;
private String icerik;
private String fiyat;
private List<String> gallery;
// Constructors, getters and setters…
}
Here is the code to parse
private List<Veri> parseJson(String json) {
List<Veri> veriList = new ArrayList<Veri>();
List<String> galleryImages = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray veriArray = jsonObject.getJSONArray("veri");
int nVeri = veriArray.length();
for (int i = 0; i < nVeri; i++) {
JSONObject veriObject = veriArray.getJSONObject(i);
long id = Long.valueOf(veriObject.getString("id"));
String date = veriObject.getString("tarih");
String baslik = veriObject.getString("baslik");
String kImaj = veriObject.getString("kImaj");
String kisaAciklama = veriObject.getString("kisaAciklama");
String icerik = veriObject.getString("icerik");
String fiyat = veriObject.getString("fiyat");
JSONArray galleryImageArray = veriObject.getJSONArray("Gallery");
int nImages = galleryImageArray.length();
for(int j = 0; j < nImages; i++) {
galleryImages.add(galleryImageArray.getString(j));
}
Veri veri = new Veri();
veri.setId(id);
veri.setDate(date);
veri.setBaslik(baslik);
veri.setKImagj(kImaj);
veri.setKisaAciklama(kisaAciklama);
veri.setFiyat(fiyat);
veri.setGallery(galleryImages);
veriList.add(veri);
}
} catch (JSONException e) {
e.printStackTrace();
}
return veriList;
}
This could help!
you can use Gson by defining objects accordingly.
for Arrays, naturally there won't be field names, therefore these can be parsed into List.
here comes an example using the response for this url
http://kilimmobilya.com.tr/mobileservices/default.aspx?i=yeniUrunler
JsonObject in the response array is;
{
id: "1436",
tarih: "08.10.2012",
baslik: "Ares Plazma TV Ünitesi",
kImaj: "http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/210x120/Ares-Plazma-VS1-00.jpg",
kisaAciklama: "",
icerik: "",
fiyat: "799",
Gallery: [
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-01.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-02.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-01.jpg"
]
},
create a Java object as;
public class Urun implements Serializable {
private static final long serialVersionUID = 1L;
#Expose public String id;
#Expose public String tarih;
#Expose public String baslik;
#Expose public String kImaj;
#Expose public String kisaAciklama;
#Expose public String icerik;
#Expose public String fiyat;
#Expose public List<String> Gallery;// notice this is a List of String
}
then you can easily parse the JsonObject into defined class. example using Gson
Urun urun = (new Gson()).fromJson(jsonObj, Urun.class);
hope this helps...
Related
I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();
I am also getting ArrayListIndexOutofBound when I am pressing list item when the orientation is changed.As far my knowledge of android I have written Parcelable code correctly.But I think my issues are with the recycler view setup.I am confused with two declaration of my adapter.Help me
MainActivity.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyCustomAdapter.ClickListener {
private static final String STATE_LIST = "state_list";
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
Map<Integer, String> articleDates =new HashMap<>();
Map<Integer, String> articleAuthors =new HashMap<>();
ArrayList<Integer> articleIds=new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<Information> data=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
ArrayList<String> urls=new ArrayList<>();
ArrayList<String> authors=new ArrayList<>();
ArrayList<String> dateAndTimes=new ArrayList<>();
MyCustomAdapter adapter;
RecyclerView recyclerView;
AVLoadingIndicatorView av;
List<DownloadTask> tasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av= (AVLoadingIndicatorView) findViewById(R.id.avloadingIndicatorView);
av.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS article (id INTEGER PRIMARY KEY," +
" articleId INTEGER," +
" url VARCHAR," +
" title VARCHAR," +
" author VARCHAR," +
" date VARCHAR)");
if(savedInstanceState != null) {
data=savedInstanceState.getParcelableArrayList(STATE_LIST);
adapter=new MyCustomAdapter(getApplicationContext(),data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}else{
if (isOnline()) {
requestData("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} else {
updateDisplay();
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
//adapter=new MyCustomAdapter(getApplicationContext(),getData());
//adapter.setClickListener(this);
//recyclerView.setAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData(String uri) {
DownloadTask task = new DownloadTask();
task.execute(uri);
}
#Override
public void itemClicked(View view, int position) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
startActivity(i);
}
protected void updateDisplay() {
adapter=new MyCustomAdapter(getApplicationContext(),getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_LIST, data);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (tasks.size() == 0) {
av.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM article");
for (int i = 0; i < 15; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleDate=jsonObject.getString("time");
String articleAuthor=jsonObject.getString("by");
long unixSeconds = Long.valueOf(articleDate);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // the format of your date
String formattedarticleDate = sdf.format(date);
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
articleDates.put(Integer.valueOf(articleId), formattedarticleDate);
articleAuthors.put(Integer.valueOf(articleId), articleAuthor);
String sql = "INSERT INTO article (articleId, url, title, author, date) VALUES (? , ? , ? , ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleAuthor);
statement.bindString(5, formattedarticleDate);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tasks.remove(this);
if (tasks.size() == 0) {
av.setVisibility(View.INVISIBLE);
}
updateDisplay();
}
}
private List<Information> getData() {
/*List<Information> data=new ArrayList<>();
for(int i=0;i<20;i++){
titles.add(i,"Wikileaks Asssange wins UN ruling on arbitrary detention");
url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");
date.add(i,"3 hrs");
author.add(i,"aburan28");
}
for(int i=0;i<20;i++){
Information current=new Information();
current.title=titles.get(i);
current.url=url.get(i);
current.author=author.get(i);
current.date=date.get(i);
data.add(current);
}
return data;*/
Cursor c = articlesDB.rawQuery("SELECT * FROM article", null);
try {
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
int authorIndex = c.getColumnIndex("author");
int dateIndex = c.getColumnIndex("date");
c.moveToFirst();
titles.clear();
//urls.clear();
authors.clear();
dateAndTimes.clear();
int i=0;
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
authors.add(c.getString(authorIndex));
dateAndTimes.add(c.getString(dateIndex));
Information current=new Information();
current.title=titles.get(i);
current.url=urls.get(i);
current.author=authors.get(i);
current.date = dateAndTimes.get(i);
data.add(current);
i++;
c.moveToNext();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
c.close();
}
return data;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
if (id == R.id.action_about) {
startActivity(new Intent(getApplicationContext(),About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
Information.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
public String title;
public String author;
public String date;
public String url;
public Information(){
}
protected Information(Parcel in) {
title = in.readString();
author = in.readString();
date = in.readString();
url = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
#Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
#Override
public Information[] newArray(int size) {
return new Information[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(date);
dest.writeString(url);
}
}
Log Cat Error
02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reader.ashishyadav271.hackernewsmaterial, PID: 8369
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.reader.ashishyadav271.hackernewsmaterial.MainActivity.itemClicked(MainActivity.java:137)
at com.reader.ashishyadav271.hackernewsmaterial.MyCustomAdapter$MyViewHolder.onClick(MyCustomAdapter.java:77)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Now I get it after years.I would have simply used.
FLAG_ACTIVITY_CLEAR_TOP - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
I have made a custom adapter for seting to a listView in android,I am paring some jsondata and want to set in into a list view,I have tried as belo but its not workig,My code as below,pls help me .
myactivity.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CategoryAdapter;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.ServiceHandler;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class ProSubCategoryActivity extends Activity {
int flag;
public Header header;
public TextView title;
Bitmap bitmap;;
private ProductAdapter productContent;
private CategoryAdapter categoryContent;
// PRODUCTS....
// arrayLists......
public static ArrayList<String> productArray;
public static ArrayList<String> categoryArray;
//
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
String name;
ListView lv;
JSONObject jsonObj;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
private ProgressDialog pDialog;
Intent in = null;
// new
public String proname;
public String prodesc;
public String proimg;
public String proMinOrderQty;
public String proMinPrice;
public String proMaxPrice;
public String proTerms;
public String proId;
// new
// URL to get contacts JSON
private static String url = "http://yehki.epagestore.in/app_api/categories.php";
private static String mainurl = "http://yehki.epagestore.in/";
public String suburl = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
this.header = (Header) findViewById(R.id.headersubcat);
title = (TextView) findViewById(R.id.title);
// getting intent data
categoryArray = new ArrayList<String>();
productArray = new ArrayList<String>();
in = getIntent();
lv = (ListView) findViewById(R.id.list);
categoryContent = new CategoryAdapter(this, categoryArray);
// Get JSON values from previous intent
try {
catid = in.getStringExtra(Const.TAG_CAT_ID);
name = in.getStringExtra(Const.TAG_CAT_NAME);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("::::::::::::::MY CATEGORY ID::::::::::::::IN SUB "
+ catid);
subcategoryList = new ArrayList<HashMap<String, String>>();
productList = new ArrayList<HashMap<String, String>>();
suburl = "http://yehki.epagestore.in/app_api/categories.php?"
+ Const.TAG_CAT_ID + "=" + catid;
System.out.println("::::::::::::::::MY SUBCATEGORY URL::::::::::::"
+ suburl);
title.setText(name);
// Displaying all values on the screen
new GetSubCategories().execute();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
if (flag == 0) {
String catname = ((TextView) view.findViewById(R.id.name))
.getText().toString();
in = new Intent(getApplicationContext(),
SubCategoryTwoActivity.class);
in.putExtra(Const.TAG_CAT_NAME, catname);
in.putExtra(Const.TAG_CAT_ID, catid);
startActivity(in);
} else {
in = new Intent(getApplicationContext(),
ProductDetailActivity.class);
proname = ((TextView) view.findViewById(R.id.product_label))
.getText().toString();
proId = ((TextView) view.findViewById(R.id.pro_id))
.getText().toString();
System.out
.println(":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
+ proname
+ " proDuct Id::::::::::::>>>>>>>>>"
+ proId);
in.putExtra(Const.TAG_PRODUCT_ID, proId);
in.putExtra(Const.TAG_PRODUCT_NAME, proname);
in.putExtra(Const.TAG_PRODUCT_IMG, proimg);
in.putExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY, proMinOrderQty);
in.putExtra(Const.TAG_PRODUCT_MIN_PRICE, proMinPrice);
in.putExtra(Const.TAG_PRODUCT_MAX_PRICE, proMaxPrice);
in.putExtra(Const.TAG_PRODUCT_DESCRIPTION, prodesc);
in.putExtra(Const.TAG_PRODUCT_PAYMENT_TERMS, proTerms);
/*
* in.putExtra(TAG_CAT_NAME, p); in.putExtra(TAG_CAT_ID,
* catid);
*/
startActivity(in);
}
}
});
}
private class GetSubCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ProSubCategoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::"
+ suburl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(suburl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_CAT_LlIS)) {
System.out
.println("::::::::::::::::true::::::::::::::::"
+ jsonObj.has(Const.TAG_CAT_LlIS));
subcategories = jsonObj
.getJSONArray(Const.TAG_CAT_LlIS);
if (subcategories != null
&& subcategories.length() != 0) {
// looping through All Contacts
flag = 0;
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ subcategories.length());
for (int i = 0; i < subcategories.length(); i++) {
JSONObject c = subcategories.getJSONObject(i);
id = c.getString(Const.TAG_CAT_ID);
String name = c.getString(Const.TAG_CAT_NAME);
// tmp hashmap for single category
/*
* HashMap<String, String> subcategory = new
* HashMap<String, String>();
*
* // adding each child node to HashMap key =>
* // value subcategory.put(Const.TAG_CAT_ID,
* id); subcategory.put(Const.TAG_CAT_NAME,
* name);
*
* // adding contact to contact list
* subcategoryList.add(subcategory);
*/
// new adde 3=04=2014
// categoryArray.add(id);
categoryArray.add(name);
System.out
.println("::::::::::My category:::::::"
+ categoryArray.get(i)
.toString().trim());
}
}
} else if (jsonObj.has(Const.TAG_PRODUCT_LlST)) {
flag = 1;
System.out
.println("::::::::::::::::true::::::::::::::::"
+ jsonObj.has(Const.TAG_PRODUCT_LlST));
products = jsonObj.getJSONArray(Const.TAG_PRODUCT_LlST);
if (products != null && products.length() != 0) {
// looping through All Contacts
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ flag);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
id = c.getString(Const.TAG_PRODUCT_ID);
String proname = c
.getString(Const.TAG_PRODUCT_NAME);
String prodesc = c
.getString(Const.TAG_PRODUCT_DESCRIPTION);
String proimg = Const.API_HOST + "/"
+ c.getString(Const.TAG_PRODUCT_IMG);
System.out
.println(":::::::::::::::My Image Url:::::::::::::"
+ proimg);
String proMinOrderQty = c
.getString(Const.TAG_PRODUCT_MIN_ORDER_QTY);
String proMinPrice = c
.getString(Const.TAG_PRODUCT_MIN_PRICE);
String proMaxPrice = c
.getString(Const.TAG_PRODUCT_MAX_PRICE);
String proTerms = c
.getString(Const.TAG_PRODUCT_PAYMENT_TERMS);
System.out
.println(":::::::::::::My prododuct name+++++++:::::::::::::"
+ proname);
System.out
.println(":::::::::::::My prododuct image+++++++:::::::::::::"
+ proimg);
System.out
.println(":::::::::::::My prododuct min order qty+++++++:::::::::::::"
+ proMinOrderQty);
// tmp hashmap for single category
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
product.put(Const.TAG_PRODUCT_ID, id);
product.put(Const.TAG_PRODUCT_NAME, proname);
product.put(Const.TAG_PRODUCT_IMG, proimg);
product.put(Const.TAG_PRODUCT_MIN_ORDER_QTY,
proMinOrderQty);
product.put(Const.TAG_PRODUCT_DESCRIPTION,
prodesc);
// adding contact to contact list
productList.add(product);
}
}
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out
.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
if (flag == 0) {
lv.setAdapter(categoryContent);
} else {
Toast.makeText(ProSubCategoryActivity.this, "Please wait", 1)
.show();
/*
* ListAdapter adapter = new SimpleAdapter(
* ProSubCategoryActivity.this, productList,
* R.layout.activity_single_produt, new String[] {
* Const.TAG_PRODUCT_ID, Const.TAG_PRODUCT_NAME,
* Const.TAG_PRODUCT_IMG, Const.TAG_PRODUCT_MIN_ORDER_QTY,
* Const.TAG_PRODUCT_DESCRIPTION }, new int[] {
* R.id.product_label, R.id.iv_product_img, R.id.min_qty,
* R.id.pro_desc, R.id.pro_id }); setListAdapter(adapter);
*/
}
}
}
}
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.yehki.R;
public class CategoryAdapter extends BaseAdapter {
private ArrayList<String> categoryArray;
private Context mContext;
public CategoryAdapter(Context paramContext,
ArrayList<String> paramArrayList) {
this.mContext = paramContext;
this.categoryArray = paramArrayList;
}
public int getCount() {
return this.categoryArray.size();
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.categoryArray.addAll(paramArrayList);
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.categoryName.setText(categoryArray.get(paramInt)
.indexOf(0));
return paramView;
}
static class Viewholder {
private TextView categoryName;
}
}
I changed your code , try this now
public class CategoryAdapter extends BaseAdapter {
private ArrayList<String> categoryArray;
private Context mContext;
private Viewholder localViewholder = null;
public CategoryAdapter(Context paramContext,
ArrayList<String> paramArrayList) {
this.mContext = paramContext;
this.categoryArray = paramArrayList;
}
public int getCount() {
return this.categoryArray.size();
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.categoryArray.addAll(paramArrayList);
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
if (paramView == null) {
localViewholder = new Viewholder();
paramView = localLayoutInflater.inflate(R.layout.list_item,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.categoryName.setText(categoryArray.get(paramInt)
.indexOf(0));
return paramView;
}
static class Viewholder {
private TextView categoryName;
}
}
I am working on app which communicate the web server. I want two methods which call by thread and also need two handler method, which used to update UI . 1 thread method and handler method need to fetch data and update UI at start of the activity. 2 thread method and handler method need to post back data on server.
How I implement this.
My code of this class...
package com.edoc.doctor;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.edoc.libraries.FetchMedicines;
import com.edoc.libraries.Functions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class AddPatient extends Activity implements Runnable, OnClickListener
{
public static final String appDoctor = "AppDoctor";
public String KEY_SUCCESS = "success";
private String success;
private ProgressDialog pd;
private JSONObject jsonObj;
private boolean addNewPatient;
private EditText email;
private EditText phone;
private EditText name;
private EditText dob;
private EditText lowBPMedicineInstructions;
private EditText highBPMedicineInstructions;
private EditText hyperLowBPMedicineInstructions;
private EditText hyperHighBPMedicineInstructions;
private Spinner lowBPMedicine;
private Spinner highBPMedicine;
private Spinner hyperLowBPMedicine;
private Spinner hyperHighBPMedicine;
private Button addPatient;
private String strEmail;
private String strPhone;
private String strName;
private String strDob;
private String strLowBPMedicineInstructions;
private String strHighBPMedicineInstructions;
private String strHyperLowBPMedicineInstructions;
private String strHyperHighBPMedicineInstructions;
private String strLowBPMedicine;
private String strHighBPMedicine;
private String strHyperLowBPMedicine;
private String strHyperHighBPMedicine;
private ArrayAdapter<String> dataAdapter;
private ArrayList<String> medicines;
private ArrayList<Integer> medicineIDs;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_patient);
medicines = new ArrayList<String>();
medicineIDs = new ArrayList<Integer>();
addPatient = (Button) findViewById(R.id.ib_add_patient);
addPatient.setOnClickListener(this);
email = (EditText) findViewById(R.id.iet_add_patient_email);
phone = (EditText) findViewById(R.id.iet_add_patient_phone);
name = (EditText) findViewById(R.id.iet_add_patient_name);
dob = (EditText) findViewById(R.id.iet_add_patient_date_of_birth);
lowBPMedicineInstructions = (EditText) findViewById(R.id.iet_low_description);
highBPMedicineInstructions = (EditText) findViewById(R.id.iet_high_description);
hyperLowBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_low_description);
hyperHighBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_high_description);
lowBPMedicine = (Spinner) findViewById(R.id.isp_low_medicine);
highBPMedicine = (Spinner) findViewById(R.id.high_medicine);
hyperLowBPMedicine = (Spinner) findViewById(R.id.hyper_low_medicine);
hyperHighBPMedicine = (Spinner) findViewById(R.id.hyper_high_medicine);
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, medicines);
final int did = getID();
// pd = ProgressDialog.show(getApplicationContext(), "Working..", "Connect To Server", true,false);
new Thread(new Runnable()
{
public void run()
{
Functions fun = new Functions();
jsonObj = fun.fetchMedicines(did);
handler.sendEmptyMessage(0);
}
}).start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
try {
Log.e("try","try");
success = jsonObj.getString("success");
Log.e("success",success);
Log.e("add",""+addNewPatient);
if(success.equals("1") && !addNewPatient)
{
JSONArray m = jsonObj.getJSONArray("medicines");
// looping through All Contacts
for(int i = 0; i < m.length(); i++)
{
JSONObject c = m.getJSONObject(i);
String name = c.getString("medicine");
int id = c.getInt("id");
Log.e("m name",name+" "+id);
medicines.add(name);
medicineIDs.add(id);
}
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
highBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperLowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperHighBPMedicine.setAdapter(dataAdapter);
}
else if(success.equals("1") && addNewPatient)
{
Log.e("success", ""+addNewPatient);
pd.dismiss();
Toast.makeText(getApplicationContext(), "Patient Add Successfully",Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Server down",Toast.LENGTH_LONG).show();
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public int getID()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(appDoctor,mode);
Editor editor = mySharedPreferences.edit();
return mySharedPreferences.getInt("id",0);
}
#Override
public void run()
{
Functions function = new Functions();
jsonObj = function.addPatient(strEmail,strPhone,strName,strDob,strLowBPMedicine
,strHighBPMedicine,strHyperHighBPMedicine,strHyperLowBPMedicine,strLowBPMedicineInstructions
, strHighBPMedicineInstructions, strHyperLowBPMedicineInstructions, strHyperHighBPMedicineInstructions, getID());
addNewPatient = true;
Log.e("run", ""+addNewPatient);
handler.sendEmptyMessage(0);
}
#Override
public void onClick(View v)
{
Log.e("onclick","on click");
strEmail = email.getText().toString();
strPhone = phone.getText().toString();
strName = name.getText().toString();
strDob = dob.getText().toString();
strLowBPMedicine = ""+lowBPMedicine.getSelectedItemPosition();
strHighBPMedicine = ""+highBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strLowBPMedicineInstructions = lowBPMedicineInstructions.getText().toString();
strHighBPMedicineInstructions = highBPMedicineInstructions.getText().toString();
strHyperLowBPMedicineInstructions = hyperLowBPMedicineInstructions.getText().toString();
strHyperHighBPMedicineInstructions = hyperHighBPMedicineInstructions.getText().toString();
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
Thread t = new Thread();
t.start();
}
}
This stuck on line 222
form below 3rd statement.
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
I am writing an Android application that essentially parses XML data using Fwix's API. The parsing part is working fine. Here's my class, Parser:
package com.magadistudio_student_connect_2011.com;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import android.util.Xml;
public class Parser {
//Feed Parsing Method
public ArrayList<Bakery> parse(String url) {
//Array of Episode Objects
ArrayList<Bakery> bakeries = null;
try {
//Encode the URL into a URL Object
URL bakery_feed_url = new URL(url);
//Open a Connection to the feed
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(bakery_feed_url.openConnection().getInputStream(), null);
}
finally {
}
int event_type = parser.getEventType();
Bakery current_bakery = null;
boolean done = false;
//Parse the feed, start reading throughout the feed from top to bottom
while (event_type != XmlResourceParser.END_DOCUMENT && !done) {
String tag_name = null;
switch (event_type) {
//Found the start of the feed
case XmlResourceParser.START_DOCUMENT:
bakeries = new ArrayList<Bakery>();
break;
//Found a start tag
case XmlResourceParser.START_TAG:
//apply the data to our Episode object based on the tag name
tag_name = parser.getName();
if (tag_name.equalsIgnoreCase("place")) {
current_bakery = new Bakery();
}
else if(current_bakery != null) {
if (tag_name.equalsIgnoreCase("phone_number")){
current_bakery.setPhone(parser.nextText());
}else if(tag_name.equalsIgnoreCase("city")){
current_bakery.setCity(parser.nextText());
}else if(tag_name.equalsIgnoreCase("province")){
current_bakery.setState(parser.nextText());
}else if(tag_name.equalsIgnoreCase("address")){
current_bakery.setAddress(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lat")){
current_bakery.setLatitude(parser.nextText());
//lat = Integer.parseInt(parser.getAttributeValue(null,"lat"));
}else if(tag_name.equalsIgnoreCase("postal_code")){
current_bakery.setZip(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lng")){
current_bakery.setLongitude(parser.nextText());
//lon = Integer.parseInt(parser.getAttributeValue(null,"lng"));
}else if(tag_name.equalsIgnoreCase("name")){
current_bakery.setPlace_name(parser.nextText());
}
}
break;
//An end tag has been reached
case XmlResourceParser.END_TAG:
tag_name = parser.getName();
//End of an Episode Item
if (tag_name.equalsIgnoreCase("place") && current_bakery != null) {
bakeries.add(current_bakery);
//Reached the end of all bakeries, no more data to collect
}
else if (tag_name.equalsIgnoreCase("places")){
done = true;
}
break;
}
event_type = parser.next();
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
//Return the Episode Array
return bakeries;
}
}
And here is my overlay class, Overlay:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class StudentItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public StudentItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public StudentItemizedOverlay(Drawable defaultMarker, Context context){
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
// Toast.makeText(StudentItemizedOverlay.this, "Hello", Toast.LENGTH_LONG).show();
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
And here is class BakeryActivity:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class BakeryActivity extends Activity implements OnItemClickListener {
//RSS Feed URL
private final String CGR_FEED_URL = "http://www.codinggreenrobots.com/episodes/rss.xml";
//xml new feed
private final String SCHOOLS_URL = "http://www.fizber.com/xml_data/xml_school_data.xml?state=wa&city=spokane";
private final String BAKERY_RSS = "apigoeshere";
//XML Widgets
private ListView listview_bakery;
private ProgressBar progress_bar;
//Arrays of Episode Data
private ArrayList<String> bakery_name;
private ArrayList<String> bakery_address;
private ArrayList<String> bakery_phone;
private ArrayList<String> bakery_latitude;
private ArrayList<String> bakery_longitude;
private ArrayList<String> bakery_state;
private ArrayList<String> bakery_zip;
private ArrayList<String> bakery_city;
/*private ArrayList<String> school_latitude;
private ArrayList<String> school_longitude;
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bakery_view);
//XML Widgets by ID
listview_bakery = (ListView) findViewById(R.id.listview_bakeries);
listview_bakery.setOnItemClickListener(this);
/* ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.drawable.colors));
listview_bakery.setDivider(sage);
listview_bakery.setDividerHeight(1);*/
progress_bar = (ProgressBar) findViewById(R.id.progress_bar_bakery);
//Make Progress Bar Invisible
progress_bar.setVisibility(ProgressBar.INVISIBLE);
//Initialize Arrays
bakery_name = new ArrayList<String>();
bakery_address = new ArrayList<String>();
bakery_phone = new ArrayList<String>();
bakery_latitude = new ArrayList<String>();
bakery_longitude = new ArrayList<String>();
bakery_state = new ArrayList<String>();
bakery_zip = new ArrayList<String>();
bakery_city = new ArrayList<String>();
//school_latitude = new ArrayList<String>();
//school_longitude = new ArrayList<String>();
downloadBakeries(BAKERY_RSS);
}
private void downloadBakeries(String Url) {
//Make Progress Bar Visible While Downloading Feed
progress_bar.setVisibility(ProgressBar.VISIBLE);
Log.d("CGRParser", "Downloading Feed");
//Start an ASync Thread to take care of Downloading Feed
new DownloadBakeries().execute(Url);
}
private class DownloadBakeries extends AsyncTask<String, Integer, ArrayList<Bakery>> {
#Override
protected ArrayList<Bakery> doInBackground(String... url) {
//Download and Parse Feed
Parser parser = new Parser();
ArrayList<Bakery> bakeries = new ArrayList<Bakery>();
bakeries = parser.parse(url[0]);
return bakeries;
}
#Override
protected void onPostExecute(ArrayList<Bakery> result) {
//Feed has been Downloaded and Parsed, Display Data to User
Log.d("CGRParser", "Feed Download Complete");
//Toast.makeText(BakeryActivity.this, "onPost", Toast.LENGTH_SHORT).show();
displayBakeries(result);
}
}
private void displayBakeries(ArrayList<Bakery> bakeries) {
//Create String Arrays to seperate titles and dates
Log.d("CGRParser", "Displaying Episode Titles To User");
ArrayList<String> bakery_name = new ArrayList<String>();
ArrayList<String> bakery_address = new ArrayList<String>();
ArrayList<String> bakery_phone = new ArrayList<String>();
ArrayList<String> bakery_latitude = new ArrayList<String>();
ArrayList<String> bakery_longitude = new ArrayList<String>();
ArrayList<String> bakery_state = new ArrayList<String>();
ArrayList<String> bakery_zip = new ArrayList<String>();
ArrayList<String> bakery_city = new ArrayList<String>();
//ArrayList<String> school_longitude = new ArrayList<String>();
for (Bakery bakery : bakeries) {
//Log.d("CGRParser", "Episode Title: " + episode.getTitle());
bakery_phone.add(bakery.getPhone());
bakery_name.add(bakery.getPlace_name());
bakery_address.add(bakery.getAddress());
bakery_latitude.add(bakery.getLatitude());
bakery_longitude.add(bakery.getLongitude());
bakery_state.add(bakery.getState());
bakery_zip.add(bakery.getZip());
bakery_city.add(bakery.getCity());
//school_longitude.add(episode.getLongitude());
}
//Toast.makeText(BakeryActivity.this, "DisplayBakeries", Toast.LENGTH_SHORT).show();
this.bakery_phone = bakery_phone;
this.bakery_name = bakery_name;
this.bakery_address = bakery_address;
this.bakery_latitude = bakery_latitude;
this.bakery_longitude = bakery_longitude;
this.bakery_state = bakery_state;
this.bakery_zip = bakery_zip;
this.bakery_city = bakery_city;
//int myNum = 0; try { myNum = Integer.parseInt(bakery_latitude.getText().toString()); } catch(NumberFormatException nfe) { System.out.println("Could not parse " + nfe); }
//Create a ListAdapter to Display the Titles in the ListView
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.bakery_row, R.id.title, bakery_name);
listview_bakery.setAdapter(adapter);
//Set Progress Bar Invisible since we are done with it
progress_bar.setVisibility(ProgressBar.INVISIBLE);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(BakeryActivity.this, Map.class));
//Display the Title and Date to the user when they click on an episode
Toast.makeText(this, "Name:" + bakery_name.get(position) + "\nphone: " + bakery_phone.get(position)+
"\nState: "+ bakery_state.get(position) + "\nAddress: "+ bakery_address.get(position)
+ "\nZip: "+ bakery_zip.get(position)+ "\nLat: " +bakery_latitude.get(position)+ "\nlon: "+ bakery_longitude.get(position), Toast.LENGTH_LONG).show();
}
}
I am able to do the XML parsing work fine, but THE PROBLEM is I can't figure out how to get the "lat" and "lng" that I have parsed (and put then into an ArrayList of Strings) and convert them into integers so I can show markers of the respective latitude and longitude location on the map.
OK, so Android's Google Maps native location API uses integers with 6 digits following the decimal point. Therefore, you want to remove the "." from the strings of integers you parsed out. Then, simply do a parseInt to attain the coordinates. With that, drop them into GeoPoints and add them to the overlay. It should be no problem.
Unless I'm missing something here, which is possible.