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.
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();
Im trying to trigger an event when i return to an activity hitting the back button.
what i want to do is when i go back with the backbutton reload some items. Is there any way to do this?
here is my Main Activity where i want to do the "reload" of data, Some thing like "onResume" or "onReEnter"
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ActivityTemporadaJson extends AppCompatActivity {
private String Nombre;
private int IdTmdb;
private String Tipo;
private int NumeroTemp;
private DBHelper mydb;
private ProgressDialog pDialog;
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original";
private Temporada temp;
private TextView nombrePelicula;
private ImageView fotoPortada;
private TextView sinopsis;
private TextView NumEpsVal;
private TextView fechaLanzVal;
private ArrayList<Episodio> episodios;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private RecyclerAdapterEpisodio mAdapterEp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temporada_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent recep = this.getIntent();
episodios = new ArrayList<>();
Nombre = recep.getStringExtra("Nombre");
Tipo = recep.getStringExtra("Tipo");
IdTmdb = Integer.parseInt(recep.getStringExtra("idSerie"));
NumeroTemp = Integer.parseInt(recep.getStringExtra("NumTemp"));
this.setTitle(Nombre);
nombrePelicula = (TextView) this.findViewById(R.id.NombrePelicula);
fotoPortada = (ImageView) this.findViewById(R.id.FotoPortada);
sinopsis = (TextView) this.findViewById(R.id.Sinopsis);
NumEpsVal = (TextView) this.findViewById(R.id.NumEpsVal);
fechaLanzVal = (TextView) this.findViewById(R.id.FechaLanzVal);
recyclerView = (RecyclerView) this.findViewById(R.id.recyclerviewEpisodios);
mydb = new DBHelper(this);
if (Tipo.equalsIgnoreCase("SQL")) {
Cursor res = mydb.getResultQuery("SELECT count(e.Visto) as numVisto FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp + " and e.visto = 1");
res.moveToFirst();
int NumVisto = res.getInt(0);
mydb.UpdateEpsVistos(NumVisto, IdTmdb, NumeroTemp);
TextView NumEpsVis = (TextView) this.findViewById(R.id.EpsVis);
TextView NumEpsVisVal = (TextView) this.findViewById(R.id.EpsVisVal);
NumEpsVis.setVisibility(View.VISIBLE);
NumEpsVisVal.setVisibility(View.VISIBLE);
AQuery androidAQuery = new AQuery(this);
res = mydb.getResultQuery("SELECT Nombre, Sinopsis, FechaInicio, Poster, NumeroEpisodios,EpisodiosVistos FROM Temporada WHERE IdTMDB = " + IdTmdb + " and NumeroTemporada = " + NumeroTemp);
res.moveToFirst();
nombrePelicula.setText(res.getString(0));
sinopsis.setText(res.getString(1));
fechaLanzVal.setText(res.getString(2));
androidAQuery.id(fotoPortada).image(res.getString(3), true, true, 150, 0);
NumEpsVal.setText(Integer.toString(res.getInt(4)));
NumEpsVisVal.setText(Integer.toString(res.getInt(5)));
Cursor resEps = mydb.getResultQuery("SELECT e.Nombre, e.NumeroEpisodio, e.NumeroTemporada, e.FechaEmision, e.Sinopsis, e.Poster, e.Visto, e.IdEpisodio FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp);
resEps.moveToFirst();
while (resEps.isAfterLast() == false) {
boolean visto = false;
if (resEps.getInt(6) == 1) {
visto = true;
}
Episodio nuevo = new Episodio(resEps.getInt(7), 0, resEps.getString(0), resEps.getInt(1), resEps.getInt(2), resEps.getString(3), resEps.getString(4), resEps.getString(5), visto);
episodios.add(nuevo);
resEps.moveToNext();
}
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(episodios, IdTmdb, Tipo);
recyclerView.setAdapter(mAdapterEp);
} else {
new GetTemp(this).execute();
}
//mydb = new DBHelper(this);
}
private class GetTemp extends AsyncTask<Void, Void, Void> {
Context c;
public GetTemp(Context c)
{
this.c = c;
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
//https://api.themoviedb.org/3/tv/57243/season/1?api_key=5e2780b2117b40f9e4dfb96572a7bc4d&language=en-US
String url = "https://api.themoviedb.org/3/tv/"+IdTmdb+"/season/"+NumeroTemp+"?api_key="+API+"&language=es-ES";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray episodes = jsonObj.getJSONArray("episodes");
String fecha = jsonObj.getString("air_date");
String nombreSerie = jsonObj.getString("name");
int numEps = episodes.length();
int numTemp = jsonObj.getInt("season_number");
String sinop = jsonObj.getString("overview");
String poster =URLFOTO + jsonObj.getString("poster_path");
// looping through All Contacts
for (int i = 0; i < episodes.length(); i++) {
JSONObject c = episodes.getJSONObject(i);
Episodio nuevo = new Episodio();
nuevo.setSinopsis(c.getString("overview"));
nuevo.setFechaEmision(c.getString("air_date"));
nuevo.setNombreEpisodio(c.getString("name"));
nuevo.setNumeroEpisodio(c.getInt("episode_number"));
nuevo.setNumeroTemporada(c.getInt("season_number"));
nuevo.setPoster(URLFOTO + c.getString("still_path"));
episodios.add(nuevo);
}
temp = new Temporada(0, IdTmdb, nombreSerie, sinop, fecha, poster, numTemp,false, 0, numEps, episodios);
} catch (final JSONException e) {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AQuery androidAQuery=new AQuery(c);
// Dismiss the progress dialog
if (pDialog.isShowing())
{
pDialog.dismiss();
}
androidAQuery.id(fotoPortada).image(temp.getPoster(), true, true, 150,0);
String Nombre = "Temporada " + temp.getNumeroTemporada();
nombrePelicula.setText(Nombre);
sinopsis.setText(temp.getSinopsis());
NumEpsVal.setText(Integer.toString(temp.getNumeroEpisodios()));
fechaLanzVal.setText(temp.getFechaInicio());
mLinearLayoutManager = new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(temp.getEpisodios(),IdTmdb,Tipo);
recyclerView.setAdapter(mAdapterEp);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(c);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
}
You can use onRestart , which will be triggered when existing activity will be bought back to front .
As quoted in docs
Called after onStop() when the current activity is being re-displayed
to the user (the user has navigated back to it). It will be followed
by onStart() and then onResume().
so Override onRestart
#Override
public void onRestart() {
// you come back to me
}
My Problem today is that been developing an APP having a Login, A Maintenance Products (For more say), all with the database engine SQL
and create the login all Ok, the procedimeinto a normal login with user and pass ago, also believes maintaining create products, which I take as parameters the name of the product and its respective description, I add, edit, and delete, just not makes the management of search data and show me when access to the corresponding layout, using the onCreate method of my MainMenu but hey that's not the case, the relevant case is that I want to know how to do that through a button, find me the names input on a EditText or are related to the name, and tried to do this using the following code:
package com.sqldata.gst.appsql;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Created by Administrador on 05/10/2016.
*/
public class ConClientes extends MainActivity {
Conexion conexionSQL;
EditText txtCdCliente, txtNomCli;
Button btnBuscar, btnRetornar;
ProgressBar pgrCliente;
ListView lstClientes;
String idCliente;
//ResultSet rs;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.con_clientes);
conexionSQL = new Conexion();
txtCdCliente = (EditText) findViewById(R.id.txtCdCliente);
//txtNomCli = (EditText) findViewById(R.id.txtNomCli);
btnBuscar = (Button) findViewById(R.id.btnBuscar);
btnRetornar = (Button) findViewById(R.id.btnRetornar);
pgrCliente = (ProgressBar) findViewById(R.id.pgrCliente);
lstClientes = (ListView) findViewById(R.id.lstClientes);
pgrCliente.setVisibility(View.GONE);
idCliente = "";
// Evento Ejecutar Boton
btnBuscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SelectClientes selectClientes = new SelectClientes();
selectClientes.execute(""); //Cannot resolve method 'execute(java.lang.String)
}
});
}
public class FillList extends AsyncTask<String, String, String>
{
String result = "";
List<Map<String, String>> CliList = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute(){
pgrCliente.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r){
pgrCliente.setVisibility(View.GONE);
Toast.makeText(ConClientes.this, r, Toast.LENGTH_SHORT).show();
String[] from = {"A", "B", "C"};
int[] views = {R.id.lblClienteId, R.id.lblNomCli, R.id.lblCodCli};
final SimpleAdapter ADA = new SimpleAdapter(ConClientes.this, CliList, R.layout.lst_cliente,
from, views);
lstClientes.setAdapter(ADA);
lstClientes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
HashMap<String, Object> obj = (HashMap<String, Object>) ADA.getItem(arg2);
idCliente = (String) obj.get("A");
//String ClienName = (String) obj.get("B");
String ClienCod = (String) obj.get("C");
//txtNomCli.setText(ClienName);
txtCdCliente.setText(ClienCod);
}
});
}
#Override
protected String doInBackground (String... params){
try{
Connection cnSQL = conexionSQL.CONN();
if (cnSQL == null){
result = "Error en la Conexión SQL Server";
}
else{
String query = "select * from clientes";
PreparedStatement psSQL = cnSQL.prepareStatement(query);
ResultSet rsSQL = psSQL.executeQuery();
ArrayList data1 = new ArrayList();
while (rsSQL.next()){
Map<String, String> dataRec = new HashMap<String, String>();
dataRec.put("A", rsSQL.getString("idcliente"));
dataRec.put("B", rsSQL.getString("nom_cli"));
dataRec.put("C", rsSQL.getString("cod_cli"));
CliList.add(dataRec);
}
result = "Success";
}
} catch (Exception ex){
result = "Error al Buscar Datos de la Tabla Clientes";
}
return result;
}
}
public class SelectClientes extends ArrayList<String>{
String result = "";
Boolean isSuccess = false;
String ClienCod = txtCdCliente.getText().toString();
String NomCli = txtNomCli.getText().toString();
#Override //Method does not override method from its superclass
protected void onPreExecute(){
pgrCliente.setVisibility(View.VISIBLE);
}
//#Override
protected void onPostExecute(String r){
pgrCliente.setVisibility(View.GONE);
Toast.makeText(ConClientes.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess == true){
FillList fillList = new FillList();
fillList.execute("");
}
}
#Override //Method does not override method from its superclass
protected String doInBackground(String... params){
if (ClienCod.trim().equals(""))
result = "Favor de Introducir el Codigo del Cliente";
else {
try{
Connection con = conexionSQL.CONN();
if (con == null){
result = "No Hay Datos para Mostrar";
} else {
String query = "Select * from clientes where idcliente =" + idCliente;
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
result = "Busqueda de Datos Correcta";
isSuccess = true;
}
} catch (Exception ex){
isSuccess = false;
result = "Verifique los Datos";
}
}
return result;
}
}
}
Well as observed that that's my code and attempted but has two factors which are commented code the first is:
selectClientes.execute(""); // Can not resolve method 'execute (java.lang.String)
and the second in the Override
#Override //Method does not override method from its superclass
that's my niggle I do not understand how I can do to make me query consisting of editext = that will be the name or names that seeketh, and the button to execute the action of select * from, you understand me
and I would like to step I make when entering the layout from the menu to load and show me the data, without pressing anything
such as doInBackground method that's what I want to do but I guess it's in the onCreate and you will understand me if you need more details, please say, what I want is to solve that little problem
Thanks to All!!
Of course app can't resolve method execute, because ArrayList doesn't have it.
SelectClientes extends ArrayList
SelectClientes should extend AsyncTask.
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 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...