Can not see progress on Progress bar in Android - android

On button click I am calling openChannel function
fetchXML is a thread which downloads xml and sets variables. Though it takes 2-5 seconds to load new view I can see progressbar jump from 0 to 100 directly.
Also Toast in openchannel ... it loads only after new view is loaded i.e. after loadView ... which breaks the purpose for what it was written.
Toast should run before showNews() but it is getting executed after it !!!!
Why it is getting delayed ?
Any help aprreciated.
UPDATE :
HandleXML.java
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
public class HandleXML
{
private List<String> title = new ArrayList<String>();
private List<String> description = new ArrayList<String>();
private int totalNews = 0;
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject = null;
public volatile boolean parsingComplete = true;
public HandleXML(String url)
{
this.urlString = url;
}
public List<String> getTitle()
{
return title;
}
public List<String> getDescription()
{
return description;
}
public int getTotalNews()
{
return totalNews;
}
public void parseXMLAndStoreIt(XmlPullParser myParser)
{
int event;
String text=null;
boolean isItem = false, isTitle = false;
try
{
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT && totalNews < 10)
{
String name=myParser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
if(name.equals("item"))
{
isItem = true;
}
break;
case XmlPullParser.TEXT:
text = myParser.getText();
text = text.replaceAll("<.*?>", "");
break;
case XmlPullParser.END_TAG:
if(name.equals("title") && isItem)
{
title.add(text);
isItem = false;
isTitle = true;
}
else if(name.equals("description") && isTitle)
{
description.add(text);
totalNews++;
isTitle = false;
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void fetchXML()
{
Thread thread = new Thread(new Runnable(){
#Override
public void run()
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
}
MainActivity.java
import java.util.Date;
import java.util.List;
import java.util.Random;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private int titleIds[] = {R.id.news1,R.id.news2,R.id.news3,R.id.news4,R.id.news5,R.id.news6,R.id.news7,R.id.news8,R.id.news9,R.id.news10};
private int descIds[] = {R.id.desc1,R.id.desc2,R.id.desc3,R.id.desc4,R.id.desc5,R.id.desc6,R.id.desc7,R.id.desc8,R.id.desc9,R.id.desc10};
private int colorIds[] = {R.color.DarkSalmon,R.color.DarkCyan,R.color.CornflowerBlue,R.color.BlueViolet,R.color.Goldenrod,R.color.Orchid,R.color.IndianRed,R.color.MediumAquamarine,R.color.LightCoral,R.color.Teal};
private ProgressBar progress;
private HandleXML obj = null;
private int currCnt = 0;
private int rand_color = new Random().nextInt(10);
private int rand_color2 = new Random().nextInt(10);
private boolean inMain = true, inChannel = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.newsScroll).setVisibility(View.GONE);
findViewById(R.id.newsChannels).setVisibility(View.VISIBLE);
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
}
public void showNews(String url)
{
currDesc = null;
currTitle = null;
obj = null;
progress.setProgress(30);
System.out.println("30 : "+new Date());
rand_color = new Random().nextInt(10);
rand_color2 = new Random().nextInt(10);
if(rand_color == rand_color2 && rand_color == 9)
rand_color2 = 0;
else if(rand_color == rand_color2)
rand_color2 = rand_color+1;
obj = new HandleXML(url);
obj.fetchXML();
progress.setProgress(50);
while(obj.parsingComplete);
progress.setProgress(70);
if(obj.getTitle().size() >0 && obj.getDescription().size() >0)
{
List<String> title = obj.getTitle();
List<String> description = obj.getDescription();
for(int i=0; i<obj.getTotalNews(); i++)
{
Button twT = (Button) findViewById(titleIds[i]);
twT.setText(title.get(i).trim());
twT.setBackground(new ColorDrawable(getResources().getColor(colorIds[rand_color])));
Button twD = (Button) findViewById(descIds[i]);
twD.setText(description.get(i).trim());
twD.setVisibility(View.GONE);
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("AHL NEWS ALERT")
.setMessage("FAILED TO LOAD NEWS !!")
.setCancelable(false)
.setNegativeButton("Close",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
progress.setProgress(90);
}
public void openChannel(View view)
{
progress.setProgress(10);
Toast.makeText(getBaseContext(), "Loading Please Wait ... ", Toast.LENGTH_SHORT).show();
showNews("http://example.com/news.xml");
progress.setProgress(100);
findViewById(R.id.newsScroll).setVisibility(View.VISIBLE);
findViewById(R.id.newsChannels).setVisibility(View.GONE);
findViewById(R.id.newsScroll).scrollTo(0, 0);
inMain = false;
inChannel = true;
}
}

If fetchXML is using a Thread then that's how it should work. You set the progress to 10 and then call loadNews which calls fetchXML in which there is a Thread.
It takes only a fraction of second to create a Thread for you.
I suggest you use an AsyncTask which give you more control over the process of fetching and parsing the xml. You should update your ProgressBar from inside the AsyncTask. There two method for this. One is onProgressUpdate and the other would be onPostExecute.

Related

JSONArray not updating immediately

Whenever in my Popular Movies Udacity project, I click on a movie poster in the favorites movie collection, which is maintained as a database offline, the URL list gets updated correctly but the JSONArray made in the AsyncTask does not update immediately.
package com.example.android.popularmovies;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.android.popularmovies.Database.Contract;
import com.example.android.popularmovies.utilities.NetworkUtils;
import com.facebook.stetho.Stetho;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final static String BASE_POSTER_URL = "http://image.tmdb.org/t/p/w500/";
private static String OPTION = "OPTION";
TextView mNoFavorites;
// = new JSONArray();
JSONArray favoriteJsonArray;
int optionChosen;
private ProgressBar mProgessBar;
private TextView mErrorMessage;
private Button mRetry;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private URL url;
private ArrayList<String> posterList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
optionChosen = savedInstanceState.getInt(OPTION);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
//mAdapter = new MainActivityAdapter(this, posterList, null);
//mRecyclerView.setAdapter(mAdapter);
mProgessBar = findViewById(R.id.progess_bar);
mErrorMessage = findViewById(R.id.error_message);
mRetry = findViewById(R.id.retry);
mNoFavorites = findViewById(R.id.no_favorites_yet);
favoriteJsonArray = new JSONArray();
tryToConnect(new View(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.preferences, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
if (item.getItemId() == R.id.top_rated) {
mRecyclerView.setVisibility(View.VISIBLE);
mNoFavorites.setVisibility(View.INVISIBLE);
url = NetworkUtils.buildUrl("top_rated");
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
optionChosen = 1;
}
if (item.getItemId() == R.id.most_popular) {
mRecyclerView.setVisibility(View.VISIBLE);
mNoFavorites.setVisibility(View.INVISIBLE);
url = NetworkUtils.buildUrl("most_popular");
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
optionChosen = 2;
}
if (item.getItemId() == R.id.favorites) {
optionFavorites();
optionChosen = 3;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
if (optionChosen == 3)
optionFavorites();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(OPTION, optionChosen);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
/* public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
optionChosen = savedInstanceState.getInt(OPTION);
}
*/
private void optionFavorites() {
try {
String[] projection = {"movie_id", "favorite_poster_path"};
Cursor cursor = getContentResolver().query(
Contract.FavoriteMovieDatabase.CONTENT_URI,
projection,
null,
null,
null
);
ArrayList<String> posterPathArrayList = new ArrayList<>();
ArrayList<URL> urlArrayList = new ArrayList<>();
if (cursor != null && cursor.moveToFirst()) {
do {
String posterPath = cursor.getString(cursor.getColumnIndex(Contract.FavoriteMovieDatabase.FAVORITE_POSTER_PATH));
posterPathArrayList.add(BASE_POSTER_URL + posterPath);
int movieId = cursor.getInt(cursor.getColumnIndex("movie_id"));
URL favoriteURL = NetworkUtils.buildUrl("favorites", movieId);
urlArrayList.add(favoriteURL);
} while (cursor.moveToNext());
Log.d("urllist", "" + urlArrayList.toString());
new FetchFavorites().execute(urlArrayList, null, null);
mAdapter = new MainActivityAdapter(MainActivity.this, posterPathArrayList, favoriteJsonArray);
mRecyclerView.setAdapter(mAdapter);
} else {
mRecyclerView.setVisibility(View.INVISIBLE);
mNoFavorites.setVisibility(View.VISIBLE);
}
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void noConnection() {
mErrorMessage.setText(R.string.no_connection);
mErrorMessage.setVisibility(View.VISIBLE);
mRetry.setText(R.string.retry);
mRetry.setVisibility(View.VISIBLE);
}
public void tryToConnect(View v) {
try {
url = NetworkUtils.buildUrl("most_popular");
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
}
private class FetchMovies extends AsyncTask<URL, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgessBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(URL... params) {
URL searchUrl = params[0];
String searchResults = null;
try {
searchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
} catch (IOException e) {
e.printStackTrace();
}
return searchResults;
}
#Override
protected void onPostExecute(String searchResults) {
mProgessBar.setVisibility(View.INVISIBLE);
try {
posterList = new ArrayList<>();
if (searchResults != null && !searchResults.equals("")) {
JSONObject jsonObject = new JSONObject(searchResults);
JSONArray pageOne = jsonObject.getJSONArray("results");
int length = pageOne.length();
for (int i = 0; i < length; i++) {
JSONObject result = pageOne.getJSONObject(i);
String posterPath = BASE_POSTER_URL + result.getString("poster_path");
posterList.add(posterPath);
}
mAdapter = new MainActivityAdapter(MainActivity.this, posterList, pageOne);
mRecyclerView.setAdapter(mAdapter);
} else noConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class FetchFavorites extends AsyncTask<ArrayList<URL>, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(ArrayList<URL>... params) {
ArrayList<URL> urlArrayList = params[0];
ArrayList<String> stringArrayList = new ArrayList<>();
String searchResults;
URL searchUrl;
favoriteJsonArray = new JSONArray();
for (int i = 0; i < urlArrayList.size(); i++)
try {
searchUrl = urlArrayList.get(i);
searchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
stringArrayList.add(searchResults);
} catch (IOException e) {
e.printStackTrace();
}
return stringArrayList;
}
#Override
protected void onPostExecute(ArrayList<String> stringArrayList) {
for (int i = 0; i < stringArrayList.size(); i++)
try {
favoriteJsonArray.put(new JSONObject(stringArrayList.get(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
urlArrayList gets updated correctly when database changes occur, but favoriteJsonArray, which is updated inside AsyncTask, does not. Why?
There are two problems in you code:
in FetchFavorites.doInBackground(), you assign a new JSONArray() to favoriteJsonArray, but your mAdapter is still hold the old reference, which is an empty JSONArray.
you didn't call mAdapter.notifyDataSetChanged() after update the favoriteJsonArray.
You can solve the problems in to ways:
do not new JSONArray() in FetchFavorites.doInBackground(), and call mAdapter.notifyDataSetChanged() after update the favoriteJsonArray, but there is still a problem, you should clear the favoriteJsonArray every time you fetch the new data, and clear a JSONArray is kind of boring (there is no clear() method).
new JSONArray(), but edit your MainActivityAdapter, add a method like setFavorites(JSONArray array), and set the new created favoriteJsonArray to it then call mAdapter.notifyDataSetChanged().

Android get attribute value from xml

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();

My list is loading again when I am Pressing Back Button

I am also getting ArrayListIndexOutofBound when I am pressing list item when the orientation is changed.As far my knowledge of android I have written Parcelable code correctly.But I think my issues are with the recycler view setup.I am confused with two declaration of my adapter.Help me
MainActivity.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyCustomAdapter.ClickListener {
private static final String STATE_LIST = "state_list";
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
Map<Integer, String> articleDates =new HashMap<>();
Map<Integer, String> articleAuthors =new HashMap<>();
ArrayList<Integer> articleIds=new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<Information> data=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
ArrayList<String> urls=new ArrayList<>();
ArrayList<String> authors=new ArrayList<>();
ArrayList<String> dateAndTimes=new ArrayList<>();
MyCustomAdapter adapter;
RecyclerView recyclerView;
AVLoadingIndicatorView av;
List<DownloadTask> tasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av= (AVLoadingIndicatorView) findViewById(R.id.avloadingIndicatorView);
av.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS article (id INTEGER PRIMARY KEY," +
" articleId INTEGER," +
" url VARCHAR," +
" title VARCHAR," +
" author VARCHAR," +
" date VARCHAR)");
if(savedInstanceState != null) {
data=savedInstanceState.getParcelableArrayList(STATE_LIST);
adapter=new MyCustomAdapter(getApplicationContext(),data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}else{
if (isOnline()) {
requestData("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} else {
updateDisplay();
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
//adapter=new MyCustomAdapter(getApplicationContext(),getData());
//adapter.setClickListener(this);
//recyclerView.setAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData(String uri) {
DownloadTask task = new DownloadTask();
task.execute(uri);
}
#Override
public void itemClicked(View view, int position) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
startActivity(i);
}
protected void updateDisplay() {
adapter=new MyCustomAdapter(getApplicationContext(),getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_LIST, data);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (tasks.size() == 0) {
av.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM article");
for (int i = 0; i < 15; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleDate=jsonObject.getString("time");
String articleAuthor=jsonObject.getString("by");
long unixSeconds = Long.valueOf(articleDate);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // the format of your date
String formattedarticleDate = sdf.format(date);
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
articleDates.put(Integer.valueOf(articleId), formattedarticleDate);
articleAuthors.put(Integer.valueOf(articleId), articleAuthor);
String sql = "INSERT INTO article (articleId, url, title, author, date) VALUES (? , ? , ? , ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleAuthor);
statement.bindString(5, formattedarticleDate);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tasks.remove(this);
if (tasks.size() == 0) {
av.setVisibility(View.INVISIBLE);
}
updateDisplay();
}
}
private List<Information> getData() {
/*List<Information> data=new ArrayList<>();
for(int i=0;i<20;i++){
titles.add(i,"Wikileaks Asssange wins UN ruling on arbitrary detention");
url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");
date.add(i,"3 hrs");
author.add(i,"aburan28");
}
for(int i=0;i<20;i++){
Information current=new Information();
current.title=titles.get(i);
current.url=url.get(i);
current.author=author.get(i);
current.date=date.get(i);
data.add(current);
}
return data;*/
Cursor c = articlesDB.rawQuery("SELECT * FROM article", null);
try {
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
int authorIndex = c.getColumnIndex("author");
int dateIndex = c.getColumnIndex("date");
c.moveToFirst();
titles.clear();
//urls.clear();
authors.clear();
dateAndTimes.clear();
int i=0;
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
authors.add(c.getString(authorIndex));
dateAndTimes.add(c.getString(dateIndex));
Information current=new Information();
current.title=titles.get(i);
current.url=urls.get(i);
current.author=authors.get(i);
current.date = dateAndTimes.get(i);
data.add(current);
i++;
c.moveToNext();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
c.close();
}
return data;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
if (id == R.id.action_about) {
startActivity(new Intent(getApplicationContext(),About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
Information.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
public String title;
public String author;
public String date;
public String url;
public Information(){
}
protected Information(Parcel in) {
title = in.readString();
author = in.readString();
date = in.readString();
url = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
#Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
#Override
public Information[] newArray(int size) {
return new Information[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(date);
dest.writeString(url);
}
}
Log Cat Error
02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reader.ashishyadav271.hackernewsmaterial, PID: 8369
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.reader.ashishyadav271.hackernewsmaterial.MainActivity.itemClicked(MainActivity.java:137)
at com.reader.ashishyadav271.hackernewsmaterial.MyCustomAdapter$MyViewHolder.onClick(MyCustomAdapter.java:77)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Now I get it after years.I would have simply used.
FLAG_ACTIVITY_CLEAR_TOPĀ - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Android Popup help - not appearing

I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!

Starting new activity through Runnable

I check if a string is NULL in a Thread, if its null, the Handler starts
a Runnable which starts a new Activity.
Everything works fine, but, after the new activity is displayed it switches back to the calling Activity and it crashes.
Here is a code snippet.
if(username==null)
{
dialogs.dismiss();
handlers.post(new MyRunable());
}
and Runnable is
public class MyRunable implements Runnable
{
public void run(){
Toast.makeText(ListActivity.this, "Your Connection is too slow",Toast.LENGTH_LONG).show();
startActivity(new Intent(ListActivity.this,Anim.class));
}
}
Here is my Full Source
package com.cram;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BuddyListActivity extends Activity
{
String ss;
private static ProgressDialog dialogs,dialog;
private Thread downloadThreads;
boolean results=false;
Context ctx;
String[]ddd;
ListView lv1;
String [] icons;
BuddyDbAdapter adapter;
NetworkInfo netinfo;
Cursor cursor;
String values;
GetBuddy gb;
BuddyDB db;
String[] username;
String[] firstname;
String[] lastname;
String[] avatar;
String[] id;
File[] iconss;
Handler handlers;
boolean ready=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buddy);
db=new BuddyDB(BuddyListActivity.this);
Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Fortheloveofhate.ttf");
TextView btxt = (TextView) findViewById(R.id.textbuddy);
btxt.setTypeface(font);
ctx=getApplicationContext();
lv1=(ListView)findViewById(R.id.list22);
netinfo=null;
adapter=new BuddyDbAdapter(BuddyListActivity.this);
netinfo=checkDataConnection(getApplicationContext());
handlers = new Handler();
adapter.open();
if(netinfo!=null)
{
downloadThreads = (Thread) getLastNonConfigurationInstance();
if (downloadThreads != null && downloadThreads.isAlive()) {
dialog = ProgressDialog.show(this, "Download", "downloading");
}
startdownload();
}
if(netinfo==null)
{
cursor=adapter.showBuddy();
if (cursor==null||cursor.moveToFirst()==false)
{
AlertDialog.Builder buddybox = new AlertDialog.Builder(this);
buddybox.setMessage("You have No Buddies Yet douche!!");
buddybox.setNeutralButton("Okay", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getBaseContext(),Anim.class));
}
});
buddybox.setCancelable(false);
buddybox.show();
}
else
{
cursor.moveToFirst();
int j=0;
ddd=new String[cursor.getCount()];
icons=new String [cursor.getCount()];
do
{
String firstName = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_FISTNAME));
String lastname = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_LASTNAME));
String Avatar = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.AVATAR));
ddd[j]=firstName+" "+lastname;
Log.d("Test", ddd[j]);
icons[j]=Avatar;
Log.d("Test", icons[j]);
j++;
}while(cursor.moveToNext());
iconss= new File[icons.length];
Log.d("Test",icons.length+"");
for (int q = 0; q < icons.length; q++) {
iconss[q] = new File(Download.ROOT +"/"+ icons[q]+".jpg");
Log.d("Test", iconss[q].getAbsolutePath().toString());
}
//adapter.close();
lv1.setAdapter(new BuddyAdapter(BuddyListActivity.this,R.layout.list1,ddd,iconss));
onDestroy();
}
}
}
private void box() {
// TODO Auto-generated method stub
cursor=adapter.showBuddy();
if (cursor==null||cursor.moveToFirst()==false)
{
dialogs.dismiss();
AlertDialog.Builder buddybox = new AlertDialog.Builder(this);
buddybox.setMessage("You have No Buddies Yet ass!!");
buddybox.setNeutralButton("Okay", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getBaseContext(),Anim.class));
}
});
buddybox.setCancelable(false);
buddybox.show();
}
}
private NetworkInfo checkDataConnection(Context applicationContext) {
final ConnectivityManager connMgr = (ConnectivityManager)BuddyListActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo=null;
final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected()||mobile.isConnected())
{networkinfo=connMgr.getActiveNetworkInfo();
return networkinfo;
}
else
{
return null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (adapter != null) {
adapter.close();
}
}
#Override
protected void onStop()
{
super.onStop();
finish();
}
private void startdownload() {
dialogs = ProgressDialog.show(BuddyListActivity.this, "Contacting Our Servers", "Geting Your Buddies Avatar");
downloadThreads = new MyThread();
downloadThreads.start();
}
public class MyThread extends Thread {
#Override
public void run() {
try {
new Thread();
GetBuddy tt=new GetBuddy();
String xml=tt.get();
if(xml==null)
{ dialogs.dismiss();
handlers.post(new MyRunable());
ready=false;
//downloadThreads.suspend();
}
final Download cd = new Download();
results = cd.downloadBitmap();
if(results)
{
BuddyParse bp=new BuddyParse();
try {
username=bp.show(xml);
// if(username==null)
// { dialogs.dismiss();
// handlers.post(new MyRunable());
// //downloadThreads.suspend();
// }
firstname=bp.firstname();
lastname=bp.lastname();
avatar=bp.avatar();
id=bp.id();
adapter.deleteAll();
ready=true;
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// Log.d("len", username.length+"");
for(int k=0; k<username.length;k++)
{
adapter.insertBuddy(id[k], username[k], firstname[k], lastname[k], avatar[k]);
Log.d("Test", id[k]+username[k]+firstname[k]+lastname[k]+avatar[k]+"");
}
box();
cursor=adapter.showBuddy();
cursor.moveToFirst();
int i=0;
ddd=new String[cursor.getCount()];
icons=new String [cursor.getCount()];
do
{
String firstName = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_FISTNAME));
String lastname = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_LASTNAME));
String Avatar = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.AVATAR));
ddd[i]=firstName+" "+lastname;
Log.d("Test", ddd[i]);
icons[i]=Avatar;
Log.d("Test",icons[i]);
i++;
}while(cursor.moveToNext());
iconss= new File[avatar.length];
for (int k = 0; k < avatar.length; k++) {
iconss[k] = new File(Download.ROOT+"/"+avatar[k]+".jpg");
Log.d("Test", iconss[k].getAbsolutePath()+"thread");
//Log.d("Test", ddd[k]);
}
if (results&&ready)
{
dialogs.dismiss();
handlers.post(new MyRuns());
}
}
// else
// { dialogs.dismiss();
// handlers.post(new MyRunable());
//
// }
}finally {
}
}
}
public class MyRuns implements Runnable {
public void run() {
ready=true;
lv1.setAdapter(new BuddyAdapter(ctx,R.layout.list1,ddd,iconss));
onDestroy();
}
}
public class MyRunable implements Runnable {
public void run() {
//Toast.makeText(BuddyListActivity.this, "Your Connection is too slow", Toast.LENGTH_LONG).show();
startActivity(new Intent(BuddyListActivity.this,Anim.class));
}
}
}
use main thread to start your thread check runOnUiThread(Runnable action)
Setting RETURN in the try catch block and setting
android:noHistory="true" in Android Manifest for all activities fixed my problem
If you are trying to create an async task in a different thread I would recommend you to use the following class:
private final class MyRunnable extends
AsyncTask<Void, Void, Document> {
protected Document doInBackground(Void... params) {
}
protected void onPostExecute(Document result) {
}
}
You only have to change the parameters.
More info here:
http://developer.android.com/reference/android/os/AsyncTask.html
Finish your current activity when starting another activity from runnable .

Categories

Resources