I wrote an application Android to parse a XML file wich is situated online. I use JDOM and AsyncTask and it works great but only when I'm connected in WIFI.
When I'm connected in 3G, it doesn't work anymore. I've got the message "Caused by: java.net.UnknownHostException: Unable to resolve host "jeancdc.perso.sfr.fr": No address associated with hostname".
This is the log file : log.
In my Manifest.xml file, I've added the permissions :
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Could someone help me please ? Thanks by advance.
Below is my XMLReader class followed by my MainActivity class.
package fr.jcdc.exemple.jdomasynctaskxmlreader;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import android.util.Log;
public class XMLReader {
private Personnage[] personnages;
public XMLReader() {
super();
}
public void loading() {
Log.i("tag","fonction loading.");
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(new URL("http://jeancdc.perso.sfr.fr/fichierXML.xml"));
Element rootNode = document.getRootElement();
List<Element> charactersList = rootNode.getChildren("personnage");
personnages = new Personnage[charactersList.size()];
for (int i = 0; i < charactersList.size(); i++) {
Element node = (Element) charactersList.get(i);
personnages[i] = new Personnage();
personnages[i].setPrenom(node.getChildText("prenom"));
personnages[i].setNom(node.getChildText("nom"));
personnages[i].setFonction(node.getChildText("fonction"));
Log.i("tag", node.getChildText("prenom") + " " + node.getChildText("nom"));
}
}
catch (IOException ioex) {
Log.d("ioex", ioex.getMessage());
ioex.printStackTrace();
}
catch (JDOMException jdomex) {
Log.d("jdomex", jdomex.getMessage());
}
}
public Personnage[] getPersonnages() {
return personnages;
}
}
// Rajouter dans le fichier AndroidManifest.xml :
// - android:configChanges="orientation|screenSize" pour gérer le changement d'orientation
// et ainsi éviter le crash de l'application
// - la permission ACCESS_NETWORK_STATE
package fr.jcdc.exemple.jdomasynctaskxmlreader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
new GetXMLDataTask<Object>().execute();
}
else {
AlertDialogBuilder alertDialogBuilder = new AlertDialogBuilder(this);
alertDialogBuilder.setTitle("Pas de connexion");
alertDialogBuilder.setMessage("Veuillez vérifier votre connexion à Internet.");
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
private class GetXMLDataTask<XMLItem> extends AsyncTask<String, Void, List<XMLItem>> {
private XMLReader xmlReader = new XMLReader();
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Téléchargement des données");
progressDialog.setMessage("Veuillez patienter.");
progressDialog.show();
}
#Override
protected List<XMLItem> doInBackground(String... arg0) {
xmlReader.loading();
return null;
}
#Override
protected void onPostExecute(List<XMLItem> result) {
try {
List<HashMap<String, String>> liste = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashMap;
for (int i = 0 ; i < xmlReader.getPersonnages().length ; i++) {
hashMap = new HashMap<String, String>();
hashMap.put("nom", xmlReader.getPersonnages()[i].getPrenom() + " " + xmlReader.getPersonnages()[i].getNom());
hashMap.put("fonction", xmlReader.getPersonnages()[i].getFonction());
liste.add(hashMap);
}
SimpleAdapter adapter = new SimpleAdapter(getApplication(), liste,
R.layout.liste_personnages, new String[] {"nom", "fonction"},
new int[] {R.id.tv_prenom_nom, R.id.tv_fonction});
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
}
catch(NullPointerException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
#SuppressWarnings("unchecked")
HashMap<String,String> hmPersonnage = (HashMap<String,String>) l.getItemAtPosition(position);
Toast.makeText(this.getApplication(), hmPersonnage.get("nom"), Toast.LENGTH_SHORT).show();
}
}
"java.net.UnknownHostException: Unable to resolve host" Exception always occur when you don't provide access internet permission but you have added required permission then your host server is not responding within time because of internet speed, due to lac of internet speed this exception might occur.
Related
I've been following a tutorial on how to show a Json arrays on android and I constantly get "Couldn't get json from server. Check internet connection!" and I can't figure out why. My Json is being generated from a php file and this works when I'm creating a list on my browser. So I'm sure my Json works.
EDIT: What adjustments do I have to do to be able to get a read from this url?
JSON array from "https://www.googleapis.com/books/v1/volumes?q=bond"
Android:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class HomeScreen extends AppCompatActivity{
private ListView lv;
private ProgressDialog progress;
private String url="https://www.googleapis.com/books/v1/volumes?q=bond";
ArrayList<HashMap<String,String>> booklist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
booklist=new ArrayList<>();
lv= (ListView) findViewById(R.id.list);
new getBooks().execute();
}
public class getBooks extends AsyncTask<Void,Void,Void> {
protected void onPreExecute(){
super.onPreExecute();
progress=new ProgressDialog(HomeScreen.this);
progress.setMessage("Fetching JSON.,.");
progress.setCancelable(false);
progress.show();
}
protected Void doInBackground(Void...arg0){
HTTP_Handler hh = new HTTP_Handler();
String jString = hh.makeHTTPCall(url);
if (jString != null) {
try {
JSONObject jObj = new JSONObject(jString);
JSONArray books = jObj.getJSONArray("bookinfo");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String name=book.getString("name");
String author=book.getString("author");
HashMap<String, String> bookdata = new HashMap<>();
bookdata.put("name", name);
bookdata.put("author", author);
booklist.add(bookdata);
}
} catch (final JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check internet connection!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
protected void onPostExecute(Void Result){
super.onPostExecute(Result);
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter=new SimpleAdapter(
HomeScreen.this,
booklist,
R.layout.bucket_list,
new String[]{"name","author"},
new int[]{R.id.list_Name,R.id.list_author);
lv.setAdapter(adapter);
}
}
}
Does your browser have to authenticate against 'website/filename.php' to return JSON? I don't see any authentication steps going on in your code. If your code is freely available, this is probably not the issue. At first glance it appears that since now JSON is being returned from the server that this could be an issue.
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 am using below code and my textview links are clickable but i want to make specific button of whatsapp and facebook for sharing..i referred several article in stackoverflow but i want for textview. for webview i had earlier done and it was easy .please help /suggest for textview sharing. i dont want all buttons to open. i want after each listview one facebook and whatsapp icon. on click whatsapp should open with text to be shared
in textview i am adding below for whatsapp share but nothing happens
<a rel="nofollow" href="whatsapp://send?text=एक वृद्ध दंपति को लगने लगा कि उनकी क वृद्ध दंपति को लगने लगा कि उनकी याददाश्त कमजोर हो चली है। यह सुनिश्चित करने के लिये कि उन्हें कुछ नही%0A."><span class="whatsapp"> </span></a>
my java code is
tried adding this one also in java but no benefit.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
if (intent != null) {
intent.putExtra(Intent.EXTRA_TEXT, msg);
startActivity(Intent.createChooser(intent, ""));
main.java code here
package com.hindishayari.funnywall.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import com.hindishayari.funnywall.R;
import com.hindishayari.funnywall.adapter.SwipeDownListAdapter;
import com.hindishayari.funnywall.analytics.AnalyticsApplication;
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
// URLS for Fetching and Submitting to Funny Wall.
private String FetchFunnyWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/ppppppppp.php";
private String SubmitJokeToWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/hhhhhhhhhh.php";
private InterstitialAd mInterstitialAd;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeDownListAdapter adapter;
private ArrayList<String> jokesList;
private ArrayList<String> timeDateList;
String JokeString = null;
String []dataValues = new String[2];
int counter = 0;
TextView titleTextView;
AlertDialog alertDw;
AlertDialog.Builder builder;
Typeface font;
LinearLayout adViewLayout;
LinearLayout listViewLayout;
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
font = Typeface.createFromAsset(getAssets(), "HelveticaNeue-Regular.ttf");
titleTextView = (TextView) findViewById(R.id.titleID);
adViewLayout = (LinearLayout) findViewById(R.id.adViewLayoutID);
listViewLayout = (LinearLayout) findViewById(R.id.ListViewLinearLayout);
titleTextView.setTypeface(font);
dataValues[0] = "";
dataValues[1] = "";
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
jokesList = new ArrayList<>();
timeDateList = new ArrayList<>();
adapter = new SwipeDownListAdapter(this, jokesList, timeDateList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
}
);
/*
This function is to refresh the List with Swipe-Down
*/
#Override
public void onRefresh() {
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
#Override
protected void onResume() {
super.onResume();
}
/*
This function is to fetch all the jokes + dates from the server and store that into the jokesList
timeDateLis respectively
*/
private class FetchFunnyWallFromServer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return FetchFunnyWall(urls[0]);
} catch (IOException e) {
return "Sorry, We cannot retrieve credits data form the server at this moment.";
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
listView.setEnabled(false);
dataValues[0] = "";
dataValues[1] = "";
counter = 0;
jokesList.clear();
timeDateList.clear();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
swipeRefreshLayout.setRefreshing(false);
listView.setEnabled(true);
if (result.equals("OK")) {
listView.post(new Runnable() {
#Override
public void run() {
Collections.reverse(jokesList);
Collections.reverse(timeDateList);
adapter.notifyDataSetChanged();
listView.smoothScrollToPosition(0);
}
});
}
else
{
Toast.makeText(getApplicationContext(), "Network Connection Problem. Make sure that your internet is properly connected", Toast.LENGTH_SHORT).show();
}
}
}
private String FetchFunnyWall(String myurl) throws IOException, UnsupportedEncodingException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
is = conn.getInputStream();
BufferedReader textReader = new BufferedReader(new InputStreamReader(is));
String readlineText;
while ((readlineText = textReader.readLine()) != null) {
if (readlineText.length() > 0 )
{
if (readlineText.equals("****")) {
continue;
}
if (readlineText.length() < 4) {
continue;
}
for (int i = 0; i < readlineText.length(); ++i) {
if (readlineText.charAt(i) == '|') {
++counter;
continue;
}
dataValues[counter] = (dataValues[counter] + readlineText.charAt(i));
}
jokesList.add(dataValues[0]);
timeDateList.add(dataValues[1]);
counter = 0;
dataValues[0] = "";
dataValues[1] = "";
}
}
}
}
}
any help will be great
I want to show progressbar wrt to downloaded data from the web. Whether I have to create dynamically or have to reference by Id by creating it in xml.I am a little bit confused. Here is my code. Could you please tell me how?
package com.example.telugumovies;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String category ="";
String[] cat = {"Upcoming","Telugu"};
private List<String> categories ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categories = new ArrayList<String>();
int i=0;
for(i=0;i<2;i++)
{
categories.add(cat[i]+" Movies");
}
ArrayAdapter<String> myAdapter = new ArrayAdapter <String>(this,
R.layout.listview_rowlayout, R.id.tv, categories);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
Bundle giveCategory = new Bundle();
if(position == 0)
{
try {
new GetData().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
else if(position == 1)
{
giveCategory.putString("cate", cat[position]);
Intent a = new Intent(MainActivity.this,Show_Years.class);
a.putExtras(giveCategory);
startActivity(a);
}
else
{
Toast.makeText(getApplicationContext(), "Sorry This option is not Available for Now ",
Toast.LENGTH_SHORT).show();
}
//String selectedItem = (String) getListView().getItemAtPosition(position);
}
class GetData extends AsyncTask<String,Integer,String>
{
ProgressBar pb ;
protected void onPreExecute()
{
pb = new ProgressBar(MainActivity.this);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String alldata = "";
int flag=1;
String data = "";
URL url = null;
int i=0,j=0,count=0,c=0;
URLConnection con = null;
InputStream is = null;
String line = null;
try
{
url = new URL("http://www.filmibeat.com/telugu/upcoming-movies.html");
con = url.openConnection();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
//System.out.println(line);
alldata = "";
flag=0;
if(line.contains("<h3"))
{j=0;
flag=1;
for(i=0;i<line.length();i++)
{
if(line.charAt(i)=='<')
{
j=1;
}
else if(j==1 && line.charAt(i)=='>')
{
j=0;
}
else if(j==0)
{
alldata = alldata + (line.charAt(i));
}
}
}
data=data+alldata;
if(flag==1)
{
data=data+"$";
}
}
System.out.println(data);
return data;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
return data;
}
}
protected void onPostExecute(String someting)
{
Bundle givedata = new Bundle();
givedata.putString("moviedata",someting);
Intent a = new Intent(MainActivity.this,Show_upcomingmovies.class);
a.putExtras(givedata);
pb.setVisibility(View.INVISIBLE);
startActivity(a);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Using dynamically created progress bar or referencing it from an id, are both fine.
Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well.
There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted():
pDialog = new ProgressDialog(this);
pDialog.setMessage("some downloading massage");
pDialog.setIndeterminate(false);
pDialog.setMax(100); //you can adjust this
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.