HTML parsing JSoup img doesn't work - java

NEW LOGCAT
06-21 13:24:25.850: W/ActivityThread(25137): Application it.rs.esempioparsinglistview is waiting for the debugger on port 8100...
06-21 13:24:40.704: W/System.err(25137): java.net.MalformedURLException: Protocol not found: /portals/v3_2/images/background-images.jpg
06-21 13:24:40.714: W/System.err(25137): at java.net.URL.<init>(URL.java:176)
06-21 13:24:40.714: W/System.err(25137): at java.net.URL.<init>(URL.java:125)
06-21 13:24:40.724: W/System.err(25137): at it.rs.esempioparsinglistview.MainActivity$ParsingPaginaWeb.doInBackground(MainActivity.java:119)
06-21 13:24:40.724: W/System.err(25137): at it.rs.esempioparsinglistview.MainActivity$ParsingPaginaWeb.doInBackground(MainActivity.java:1)
06-21 13:24:40.724: W/System.err(25137): at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-21 13:24:40.724: W/System.err(25137): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-21 13:24:40.734: W/System.err(25137): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-21 13:24:40.744: W/System.err(25137): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-21 13:24:40.744: W/System.err(25137): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-21 13:24:40.744: W/System.err(25137): at java.lang.Thread.run(Thread.java:841)
06-21 13:29:03.541: W/ActivityThread(25327): Application it.rs.esempioparsinglistview is waiting for the debugger on port 8100...
06-21 13:29:16.984: W/System.err(25327): java.net.MalformedURLException: Protocol not found: /portals/v3_2/images/background-images.jpg
06-21 13:29:17.004: W/System.err(25327): at java.net.URL.<init>(URL.java:176)
06-21 13:29:17.004: W/System.err(25327): at java.net.URL.<init>(URL.java:125)
06-21 13:29:17.014: W/System.err(25327): at it.rs.esempioparsinglistview.MainActivity$ParsingPaginaWeb.doInBackground(MainActivity.java:118)
06-21 13:29:17.014: W/System.err(25327): at it.rs.esempioparsinglistview.MainActivity$ParsingPaginaWeb.doInBackground(MainActivity.java:1)
06-21 13:29:17.014: W/System.err(25327): at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-21 13:29:17.014: W/System.err(25327): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-21 13:29:17.024: W/System.err(25327): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-21 13:29:17.024: W/System.err(25327): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-21 13:29:17.034: W/System.err(25327): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-21 13:29:17.034: W/System.err(25327): at java.lang.Thread.run(Thread.java:841)
HTML code
<figure class="f-art-list">
<a href="/news/Cronaca/295507/news.aspx" id="MainContent_ListNews_rptNews_lnkToNews1_0" title="Ai domiciliari dopo atti incendiari nei confronti di imprenditore di Noci. Arrestati due santermani">
<img style="display: block;" data-original="http://cdn.livenetwork.it/news/295507/634903800413300428_arresto_carabinieri_HomeStandard_191x95.jpg" src="http://cdn.livenetwork.it/news/295507/634903800413300428_arresto_carabinieri_HomeStandard_191x95.jpg" class="lazy img-responsive" alt="Ai domiciliari dopo atti incendiari nei confronti di imprenditore di Noci. Arrestati due santermani" title="Ai domiciliari dopo atti incendiari nei confronti di imprenditore di Noci. Arrestati due santermani">
</a>
</figure>
Hi i have problem on parsing HTML JSoup, LogCat evidence problem on this part:
cache.immagineart.setImageBitmap(immaginiart.get(pos));
LogCat error messages
06-20 12:30:17.097: E/AndroidRuntime(15941): FATAL EXCEPTION: main
06-20 12:30:17.097: E/AndroidRuntime(15941): Process: it.rs.esempioparsinglistview, PID: 15941
06-20 12:30:17.097: E/AndroidRuntime(15941): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
06-20 12:30:17.097: E/AndroidRuntime(15941): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
06-20 12:30:17.097: E/AndroidRuntime(15941): at java.util.ArrayList.get(ArrayList.java:308)
06-20 12:30:17.097: E/AndroidRuntime(15941): at it.rs.esempioparsinglistview.ParsingArrayAdapter.getView(ParsingArrayAdapter.java:78)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.AbsListView.obtainView(AbsListView.java:2295)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.ListView.onMeasure(ListView.java:1175)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.View.measure(View.java:16521)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1231)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.View.measure(View.java:16521)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.View.measure(View.java:16521)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
06-20 12:30:17.097: E/AndroidRuntime(15941): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.View.measure(View.java:16521)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-20 12:30:17.097: E/AndroidRuntime(15941): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2553)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.View.measure(View.java:16521)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.Choreographer.doFrame(Choreographer.java:544)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.os.Handler.handleCallback(Handler.java:733)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.os.Handler.dispatchMessage(Handler.java:95)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.os.Looper.loop(Looper.java:136)
06-20 12:30:17.097: E/AndroidRuntime(15941): at android.app.ActivityThread.main(ActivityThread.java:5142)
06-20 12:30:17.097: E/AndroidRuntime(15941): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 12:30:17.097: E/AndroidRuntime(15941): at java.lang.reflect.Method.invoke(Method.java:515)
06-20 12:30:17.097: E/AndroidRuntime(15941): at dalvik.system.NativeStart.main(Native Method)
ParsingArrayAdapter.java:78 is this: cache.immagineart.setImageBitmap(immaginiart.get(pos));
This Part is for insert Bitmap in ArrayList for img
The URL parsing is: http://www.santeramolive.it/news/tutte-le-news.aspx
Mainactivity.java
public class MainActivity extends Activity {
ListView lista;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista = (ListView)this.findViewById(R.id.main_lista);//list id
//asynctask
ParsingPaginaWeb parsing = new ParsingPaginaWeb();
parsing.execute("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class ParsingPaginaWeb extends AsyncTask<String,String,String> {
ArrayList<String> titoli; //list title
ArrayList<String> descrizioni; //list description
ArrayList<String> date; // list date
ArrayList<String> categorie; // list category
ArrayList<Bitmap> immaginiart; // lista img
#Override
protected void onPreExecute()
{
titoli = new ArrayList<String>();
descrizioni = new ArrayList<String>();
date= new ArrayList<String>();
categorie= new ArrayList<String>();
immaginiart = new ArrayList<Bitmap>();
}
#Override
protected String doInBackground(String... params) {
Bitmap bitmap;
try {
Document doc = Jsoup.connect("http://www.santeramolive.it/news/tutte-le-news.aspx")
.userAgent("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22")
.timeout(30000).get();
Element listarticoli = doc.getElementsByClass("list-articles").first();
Elements articoli = listarticoli.getElementsByClass("art-list");
for(Element articolo : articoli)
{
// title
String titolo = articolo.getElementsByClass("t-art-list").first().text();
// description
String descrizione = articolo.getElementsByTag("p").first().text();
// insert in arraylist
titoli.add(titolo);
descrizioni.add(descrizione);
Elements dcs = articolo.getElementsByClass("date-tag-art-list");
for(Element dc : dcs)
{
String data = dc.getElementsByClass("date-art-list").first().text();
String categoria = dc.getElementsByClass("tag-art-list").first().text();
date.add(data); // add date
categorie.add(categoria);// add category
}
//img part
Elements imgdivs = articolo.getElementsByClass("f-art-list");
for(Element imgsdiv : imgdivs)
{
Element divimg = imgsdiv.getElementsByClass("lazy img-responsive").first();
String imgSrc = divimg.attr("src");
InputStream input = new java.net.URL(imgSrc).openStream();
bitmap = BitmapFactory.decodeStream(input);
immaginiart.add(bitmap);
}
}
} catch (Exception e) {
Log.e("ESEMPIO", "ERRORE NEL PARSING");
}
return null;
}
#Override
protected void onPostExecute(String result)
{
ParsingArrayAdapter adapter = new ParsingArrayAdapter(MainActivity.this, titoli, descrizioni, date, categorie, immaginiart);
lista.setAdapter(adapter);
}
}
}
ParsingArrayAdapter.java
public class ParsingArrayAdapter extends ArrayAdapter<String>{
//riferimenti statici alle risorse e agli id
private final static int LAYOUT = R.layout.riga_listview;
private final static int TITOLO = R.id.riga_listview_titolo;
private final static int DESCRIZIONE = R.id.riga_listview_descrizione;
private final static int DATA = R.id.riga_listview_data;
private final static int CATEGORIA = R.id.riga_listview_categoria;
private final static int IMMAGINE= R.id.riga_listview_immagine;
ArrayList<String> titoli;
ArrayList<String> descrizioni;
ArrayList<String> date;
ArrayList<String> categorie;
ArrayList<Bitmap> immaginiart;
Context c; //context
LayoutInflater inflater; //layout inflater
public ParsingArrayAdapter(Context context,ArrayList<String> titoli,ArrayList<String> descrizioni, ArrayList<String> date, ArrayList<String> categorie, ArrayList<Bitmap> immaginiart)
{
super(context,TITOLO);
this.c = context;
this.titoli = titoli;
this.descrizioni = descrizioni;
this.date= date;
this.categorie= categorie;
this.immaginiart= immaginiart;
this.inflater = LayoutInflater.from(c);
}
#Override
public int getCount()
{
return titoli.size();
}
#Override
public View getView(int pos,View view,ViewGroup parent)
{
CacheRiga cache; //cache
if(view==null)
{
// creo la view ma non l'attacco alla lista in quanto devo ancora modificare
// i testi delle textview
view = inflater.inflate(LAYOUT, parent,false);
cache = new CacheRiga();
cache.titolo = (TextView) view.findViewById(TITOLO);
cache.descrizione = (TextView) view.findViewById(DESCRIZIONE);//collego descrizione
cache.data = (TextView) view.findViewById(DATA);
cache.categoria = (TextView) view.findViewById(CATEGORIA);
cache.immagineart = (ImageView) view.findViewById(IMMAGINE);
view.setTag(cache);
}
else
{
cache = (CacheRiga) view.getTag(); dalla view
}
cache.titolo.setText(titoli.get(pos));
cache.descrizione.setText(descrizioni.get(pos));
cache.data.setText(date.get(pos));
cache.categoria.setText(categorie.get(pos));
cache.immagineart.setImageBitmap(immaginiart.get(pos));
return view;
}
private class CacheRiga {
public TextView titolo;
public TextView descrizione;
public TextView data;
public TextView categoria;
public ImageView immagineart;
}
}

Your problem is in
String imgSrc = divimg.attr("src");
because divimg== null. The stacktrace is clearly showing this. Further the app crashes. Why didn't you tell? Why didn't you post more of the logcat/stacktrace? You would have been helped sooner.
Change your code to:
Element divimg = imgsdiv.getElementsByClass("lazy img-responsive").first();
if ( divimg==null)
{
Log.e(TAG, "divimg==null: " + titolo);
immaginiart.add(null);
}
else
{
String imgSrc = divimg.attr("src");
InputStream input = new java.net.URL(imgSrc).openStream();
bitmap = BitmapFactory.decodeStream(input);
immaginiart.add(bitmap);
}
This will not decode the image but just display an empty image.

Related

How to rectify this error iin Recyclerview with database

When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}

Cannot update text in EditText inside onActivityResult

I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
            at android.app.ActivityThread.access$1100(ActivityThread.java:150)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:5225)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
            at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...

Update and remove GridView items at runtime

i am developing a project where i compare the images of two items,So if two items will have same image after clicking these items should be hide. my code is given below and this code encounter a problem. is this a logical error or any other issue? i try to solve the issue but did't resolve.. Please guide me... here is my main Activity.
MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
ImageAdapter adapter;
List<Integer> pictures;
boolean flage = false;
GridView gridView;
int save1, save2;
int img1 = -1, img2 = -1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView myimage = new ImageView(ctx);
gridView = (GridView) findViewById(R.id.gv_memory);
gridView.setAdapter(adapter);
shuffleArray();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
myimage.setImageResource(pictures.get(position));
if (flage == false) {
img1 = pictures.get(position);
flage = true;
} else if (flage == true) {
img2 = pictures.get(position);
checkResult();
flage = false;
}
}
private void checkResult() {
// TODO Auto-generated method stub
if (img1 == img2) {
adapter.pictureList.remove(img1);
adapter.pictureList.remove(img2);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Sorry!!!!",
Toast.LENGTH_LONG).show();
}
}
});
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures = new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++) {
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context context;
List<Integer> pictureList = new ArrayList<Integer>();
public ImageAdapter(Context c) {
context = c;
for (int i = 0; i < 8; i++) {
pictureList.add(R.drawable.question);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureList.size());
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView myimage = new ImageView(context);
myimage.setImageResource(pictureList.get(position));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
return myimage;
}
}
LogCat.
03-14 06:09:03.793: D/dalvikvm(2877): GC_FOR_ALLOC freed 54K, 8% free 2771K/2996K, paused 111ms, total 117ms
03-14 06:09:03.802: I/dalvikvm-heap(2877): Grow heap (frag case) to 3.943MB for 1127536-byte allocation
03-14 06:09:03.922: D/dalvikvm(2877): GC_FOR_ALLOC freed 2K, 6% free 3870K/4100K, paused 118ms, total 118ms
03-14 06:09:03.962: D/AndroidRuntime(2877): Shutting down VM
03-14 06:09:03.962: W/dalvikvm(2877): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-14 06:09:03.972: E/AndroidRuntime(2877): FATAL EXCEPTION: main
03-14 06:09:03.972: E/AndroidRuntime(2877): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.memory/com.example.memory.MainActivity}: java.lang.NullPointerException
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Looper.loop(Looper.java:137)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invoke(Method.java:525)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 06:09:03.972: E/AndroidRuntime(2877): at dalvik.system.NativeStart.main(Native Method)
03-14 06:09:03.972: E/AndroidRuntime(2877): Caused by: java.lang.NullPointerException
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.ViewConfiguration.get(ViewConfiguration.java:318)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.View.<init>(View.java:3264)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.widget.ImageView.<init>(ImageView.java:112)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.example.memory.MainActivity.onCreate(MainActivity.java:33)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Activity.performCreate(Activity.java:5133)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-14 06:09:03.972: E/AndroidRuntime(2877): ... 11 more
03-14 06:14:04.503: I/Process(2877): Sending signal. PID: 2877 SIG: 9
You have
final ImageView myimage = new ImageView(ctx);
ctz is not initialized. Its only declared as Context ctx;
You have this
gridView.setAdapter(adapter);
But you need to intialize adapter before using the same
So change to
setContentView(R.layout.main);
final ImageView myimage = new ImageView(this); //this refers to Activity context
gridView = (GridView) findViewById(R.id.gv_memory);
adapter = new ImageAdapter(this)
gridView.setAdapter(adapter);

Unable to start activity ComponentInfo; trying to create splash screen

I recently added a splash screen to my Android application to mask the loading of a JSON file, but my app crashes after finishing parsing. I've commented out and uncommented out code until I found the problematic segment, but I'm not sure why it isn't working.
The code works if I comment out the for loop from this code segment.
From MagazinePagesActivity.java:
public void loadItems() {
for (Item item : SplashActivity.downloadedItems) {
Post post = (Post) item;
for (String tag : post.tags) {
if (tag.equals(this.tag)) {
// loader.loadImage(magazine.imageURL, new
// SimpleImageLoadingListener());
Bundle bundle = new Bundle();
bundle.putString("title", post.title);
bundle.putString("article", post.article);
bundle.putString("imageURL", post.imageURL);
MagazineFragment cover = new MagazineFragment();
cover.setArguments(bundle);
coverAdapter.addNewItem(cover);
}
}
}
setContentView(vp);
}
At first, I thought it was because SplashActivity.downloadedItems wasn't properly defined, but it looks fine to me:
From SplashActivity.java:
public static ArrayList<Item> downloadedItems = new ArrayList<Item>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new RetreiveJSONTask() {
protected void onPostExecute(String JSON)
{
Log.d("SplashActivity", "Beginning parsingJSON" );
downloadedItems = parseJSON ( JSON );
Log.d("SplashActivity", "Finished parsingJSON" );
Log.d("SplashActivity", "" + SplashActivity.downloadedItems.isEmpty());
Intent i = new Intent(SplashActivity.this, MagazinePagesActivity.class);
startActivity(i);
// Closes the splash screen
finish();
}
}.execute(sourceURL());
}
From LogCat:
10-16 19:23:12.602: D/AndroidRuntime(828): Shutting down VM
10-16 19:23:12.602: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x41465700)
10-16 19:23:12.632: E/AndroidRuntime(828): FATAL EXCEPTION: main
10-16 19:23:12.632: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bruinfootball/com.dailybruin.bruinframework.channels.StoryListActivity}: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:99)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:137)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:525)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-16 19:23:12.632: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.JSONItemsActivity.onCreate(JSONItemsActivity.java:20)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryItemsActivity.onCreate(StoryItemsActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.onCreate(StoryListActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Activity.performCreate(Activity.java:5133)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-16 19:23:12.632: E/AndroidRuntime(828): ... 11 more
Not sure if it helps, but both SplashActivity and MagazinePagesActivity extend JSONItemsActivity, separately.
Thanks in advance for any help! I'm fairly new to Android, so please bear with me.
Edit: That's odd, the debug statement I put to check if the ArrayList is empty returns true, but another debug statement within parseJSON shows that things are being added. My parseJSON method:
public ArrayList<Item> parseJSON(String jsonString) {
ArrayList<Item> magazines = new ArrayList<Item>();
JSONArray jArray;
try {
jArray = new JSONArray(jsonString);
JSONObject jObject;
JSONObject image;
String img;
String title;
String subtitle;
int commentCount;
String content;
String date;
String ID;
String slug;
JSONArray array;
String[] tags;
for (int i = 0; i < jArray.length(); i++) {
jObject = jArray.getJSONObject(i);
img = jObject.getString("tall_image_url");
if (img.equals(""))
img = jObject.getString("image_url");
if (img.equals("") && !jObject.isNull("poster_image")) {
image = jObject.getJSONObject("poster_image");
img = image.getString("name");
}
title = jObject.getString("title");
subtitle = jObject.getString("subtitle");
commentCount = jObject.getInt("comment_count");
content = jObject.getString("content_html");
date = jObject.getString("creation_date");
ID = jObject.getString("id");
slug = jObject.getString("slug");
array = jObject.getJSONArray("tags_list");
tags = new String[array.length()];
for (int j = 0; j < array.length(); j++) {
tags[j] = array.getString(j);
}
for (String tag : tags) {
if (tag.equals(this.tag))
{
Post additive = new Post(img, title, subtitle,
commentCount, content, date, ID, slug, tags);
magazines.add(additive);
Log.d("SplashActivity", additive.toString());
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return magazines;
}
StoryListActivity line 27:
public void loadItems() {
(findViewById(R.id.progress_bar)).setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction()
.replace(R.id.loading, new StoryListFragment()).commit();
}
StoryItemsActivity (MagazinePagesActivity and StoryListActivity extend this class; this class extends JSONItemsActivity, which SplashActivity also extends):
package com.dailybruin.bruinframework.channels;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.dailybruin.bruinframework.R;
import com.dailybruin.bruinframework.base.BaseActivity;
import com.dailybruin.bruinframework.base.URLBuilder;
import android.os.Bundle;
public abstract class StoryItemsActivity extends JSONItemsActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public String sourceURL()
{
return URLBuilder.getPostsURL(getString(R.string.slug));
}
public ArrayList<Item> parseJSON(String jsonString) {
// Using pre-downloaded and parsed JSON
return SplashActivity.downloadedItems;
}
}
Check this part of the code. Line number 27. That is null and hence causing NPE.
Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)

Use My location Latitude Longitude and DB Latitude Longitude Calculation Distance

Use My location Latitude Longitude and DB Latitude Longitude Calculation Distance.but always error "The application AndroidGoogleMaps(process com.androidhive.googlemaps)has stopped unexpectedly.Please try again."
public class AndroidGoogleMapsActivity extends MapActivity {
public int mm[][]= new int[100][100];
double[][] rtdist= new double[50][2];
double[][] okdist= new double[50][2];
public GeoPoint[] endpp = new GeoPoint[100];
private static String KEY_SUCCESS = "success";
private MyLocationOverlay mylayer;
private MapController mapController;
private MapView mapView;
protected GeoPoint geoPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setupMap();
}
private void findViews() {
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
}
private void setupMap() {
List<Overlay> overlays = mapView.getOverlays();
mylayer = new MyLocationOverlay(this, mapView);
mylayer.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
mapView.setTraffic(true);
mapController.setZoom(17);
mapController.animateTo(mylayer.getMyLocation());
}
});
overlays.add(mylayer);
GeoPoint startpp = mylayer.getMyLocation();
String b="SELECT lat,lng FROM markers";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.execqlcmd(b);
try {
if (json.getString(KEY_SUCCESS) != null)
{
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
for(int i=0 ; i<100 ; i++) {
JSONObject json_row = json.getJSONObject("r"+i);
mm[i][0]=(int)(Double.parseDouble(json_row.getString("c0")) * 1E6) ;
mm[i][1]=(int)(Double.parseDouble(json_row.getString("c1")) * 1E6) ;
endpp[i] =new GeoPoint(mm[i][0], mm[i][1] );
MapController mc = mapView.getController();
DistanceCalculator caldist= new DistanceCalculator(6371);
for(int j = 0; j < 2; j++)
{
rtdist[j][0]=1;
rtdist[j][1]=caldist.CalculationByDistance(startpp, endpp[j]);
//startpp The location of the phone is
//endpp DB's lat lng
//To judge the results of this array is in line with the distance required by the user
if(rtdist[j][1]<=50)
{
okdist[j][0]=rtdist[j][0]; //The amount of store
okdist[j][0]=rtdist[j][1]; //Store the distance
}
}
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate();
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
AddItemizedOverlay itemizedOverlay =
new AddItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}}}}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mylayer.enableMyLocation();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mylayer.disableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class DistanceCalculator {
private double Radius;
// R = earth's radius (mean radius = 6,371km)
// Constructor
DistanceCalculator(double R) {
Radius = R;
}
public double CalculationByDistance(GeoPoint startpp, GeoPoint endpp) {
double lat1 = startpp.getLatitudeE6()/1E6;
double lat2 = endpp.getLatitudeE6()/1E6;
double lon1 = startpp.getLongitudeE6()/1E6;
double lon2 = endpp.getLongitudeE6()/1E6;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
}
}
LogCat :
05-13 14:49:44.703: D/dalvikvm(303): GC_FOR_MALLOC freed 4358 objects / 275032 bytes in 316ms
05-13 14:49:44.903: D/dalvikvm(303): GC_FOR_MALLOC freed 10567 objects / 641664 bytes in 58ms
05-13 14:49:45.063: D/dalvikvm(303): GC_FOR_MALLOC freed 4727 objects / 310440 bytes in 45ms
05-13 14:49:45.243: D/dalvikvm(303): GC_FOR_MALLOC freed 6480 objects / 394584 bytes in 48ms
05-13 14:49:45.443: D/dalvikvm(303): GC_FOR_MALLOC freed 7949 objects / 616640 bytes in 51ms
05-13 14:49:45.623: D/dalvikvm(303): GC_FOR_MALLOC freed 6072 objects / 370040 bytes in 51ms
05-13 14:49:45.813: D/dalvikvm(303): GC_FOR_MALLOC freed 4449 objects / 354128 bytes in 62ms
05-13 14:49:45.823: I/dalvikvm-heap(303): Grow heap (frag case) to 3.048MB for 87396-byte allocation
05-13 14:49:45.884: D/dalvikvm(303): GC_FOR_MALLOC freed 45 objects / 2392 bytes in 66ms
05-13 14:49:45.953: D/dalvikvm(303): GC_FOR_MALLOC freed 2 objects / 80 bytes in 67ms
05-13 14:49:45.953: I/dalvikvm-heap(303): Grow heap (frag case) to 3.129MB for 87396-byte allocation
05-13 14:49:46.013: D/dalvikvm(303): GC_FOR_MALLOC freed 0 objects / 0 bytes in 58ms
05-13 14:49:46.273: E/JSON(303): {"tag":"exesqlcmd","success":1,"error":0,"rownum":2,"colnum":2,"r0":{"c0":"23.973728","c1":"121.583641"},"r1":{"c0":"23.973827","c1":"121.585625"}}
05-13 14:49:46.293: D/AndroidRuntime(303): Shutting down VM
05-13 14:49:46.293: W/dalvikvm(303): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-13 14:49:46.313: E/AndroidRuntime(303): FATAL EXCEPTION: main
05-13 14:49:46.313: E/AndroidRuntime(303): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.googlemaps/com.androidhive.googlemaps.AndroidGoogleMapsActivity}: java.lang.NullPointerException
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.os.Looper.loop(Looper.java:123)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-13 14:49:46.313: E/AndroidRuntime(303): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 14:49:46.313: E/AndroidRuntime(303): at java.lang.reflect.Method.invoke(Method.java:521)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-13 14:49:46.313: E/AndroidRuntime(303): at dalvik.system.NativeStart.main(Native Method)
05-13 14:49:46.313: E/AndroidRuntime(303): Caused by: java.lang.NullPointerException
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity$DistanceCalculator.CalculationByDistance(AndroidGoogleMapsActivity.java:178)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity.setupMap(AndroidGoogleMapsActivity.java:106)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity.onCreate(AndroidGoogleMapsActivity.java:41)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-13 14:49:46.313: E/AndroidRuntime(303): ... 11 more
if you want to calculate distance between two geographic point you have to see those two methods in the Location Class
Location Class
you can use it like this:
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);

Categories

Resources