How Can I Update the activity(ListView) - android - android

I am using services and broadcast receiver, to launch a listview (I am using only two activity classes first as first class starts it starts service with it..in the services hitting a webservice and parsing data, n passing data into the broadcast receiver,
now the data I am getting in onreceive, and storing that data into another data...now I want this data to access in my activity class which I wl use for listView...please tell how can I do it..without making that var. static.
I also tried this thing within another way please if it is possible in that way too.
There the first screen is getting launch there I kept one button as I click on the button service will start n will do the whole job as I wrote above.....but here as I click the button another activity is being launched which is that listview but that isn't extending listActivity that is extending activity.
so I want to update that list view dynamically how can I do this?
please, any Help is Appreciable.
my code is here where I am getting stuck
public class MessageList extends Activity {
public static final String TAG = MessageList.class.getSimpleName();
Context mContext;
public static ArrayList<String> mData;
public ListView mListView;
private List<Message> messages;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.maina);
System.out.println("check bro"+mData);
System.out.println("In OnCreate of Messagelist class");
System.out.println("1st");
System.out.println("3rd");
mListView = (ListView) findViewById(R.id.mylist);
PlaceAdapter adapter = new PlaceAdapter(this, mData);
mListView.setAdapter(adapter);
}
private OnItemClickListener mItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent viewMessage = new Intent(Intent.ACTION_VIEW,Uri.parse(messages.get(arg2).getLink().toExternalForm()));
startActivity(viewMessage);
}
};
/* #Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(messages
.get(position).getLink().toExternalForm()));
this.startActivity(viewMessage);
}*/
class MessageListBroadCast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("hello");
System.out.println("final Done");
Bundle bundle = intent.getExtras();
mData = bundle.getStringArrayList("keya");
Log.d(TAG, "" + mData);
intent.putExtra("name", mData);
}
};
}
that message list is the class which is a list view
Thanks

Rather than working like this, I would use a class derived from CursorAdapter as Adapter and let your service store its results in a ContentProvider and notify changes on your ContentResolver on the same Uri you are using in the CursorAdapter. That way it will refresh automatically and your data is not lost should anything happen with your app (crash, memory,...). But I reckon this might be a bit of overhead, it all depends on what your webservice exactly does etc.

Related

How to use notifyDataSetChanged with finish()

I have a list view which show list of task, on selecting task it shows details about task, when I delete the particular task it returns to the previous activity by finish(). but it does not update the list.
I want to know how and where to use notifyDataSetChanged method and add adapter method is never used.
Other than notifyDataSetChanged() solution is also accepted :) i just want to update the list when it returns to the previous activity.
Do it with startActivityForResult(). When you create intent to open new activity open it for result. The task being deleted is your result. So when it's marked as deleted and you return to your previous activity, the result triggers and you can delete the marked item + call the notify.
More info here : http://developer.android.com/training/basics/intents/result.html
you can use the notifyDataSetChanged on the onResume method, this always update the data itself when the Activity shows
You can also notify your parent activity before finishing your current activity. You just have to register a Receiver in your main activity and all others activities will be able to notify that activity. You can even send data!
As my english is not that good, sample code :
The MainActivity class
public class MainActivity extends AppCompatActivity {
// you can define your name for your receiver as a constant,
// so you can access it from other activities if you want
public static final String MY_SUPER_INTERNAL_NOTIFICATION = "MY_SUPER_INTERNAL_NOTIFICATION";
public static final String MY_OBJECT = "my_object";
public static final String MY_OBJECT_POSITION = "my_object_position" ;
private MyCustomAdapter adapter;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
// set up your list with your adapter and data...
adapter = new MyCustomAdapter(this);
// [...] I suppose you know how to do that, I dont write everything
listView.setAdapter(adapter);
// when you click on a row from your list,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(
MainActivity.this,
SecondActivity.class
);
// you can for example put data in a Bundle and pass it to the other activity
// then on the onCreate you can use that data as you want
Bundle bundle = new Bundle();
// IMPORTANT be sure that the object you are putting in the bundle is Serializable (implements Serializable)
bundle.putSerializable(MY_OBJECT, adapter.getItem(position));
// you can also for example send the position of the row you clicked
bundle.putInt(MY_OBJECT_POSITION, position);
// put your bundle in the intent
intent.putExtras(bundle);
startActivity(intent);
}
});
// register your Receiver! don't forget to do that or you will never be notified
LocalBroadcastManager
.getInstance(this)
.registerReceiver(
broadcastReceiver,
new IntentFilter(MY_SUPER_INTERNAL_NOTIFICATION)
);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
// get the position sent by the other activity
int position = intent
.getExtras()
.getInt(SecondActivity.MY_EXAMPLE_KEY);
adapter.deleteItem(position);
}
}
};
// adapter class...
private class MyCustomAdapter extends BaseAdapter {
ArrayList<MyObject> data;
public MyCustomAdapter(Context context) {
}
public void deleteItem(int position){
// delete your item from the list of data
data.remove(position);
// dont forget to notify
notifyDataSetChanged();
}
#Override
public int getCount() {
return 0;
}
#Override
public MyObject getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
// adapter class, you can extend your favorite type of adapter
}
}
The SecondActivity class :
public class SecondActivity extends AppCompatActivity {
public static final String MY_EXAMPLE_KEY = "EXAMPLE";
private MyObject myObject;
private int myObjectPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
myObject = (MyObject) getIntent()
.getExtras()
.getSerializable(MainActivity.MY_OBJECT);
myObjectPosition = getIntent()
.getExtras()
.getInt(MainActivity.MY_OBJECT_POSITION);
// do all your stuff with your object
// before calling finish do this
beforeFinishDoThisStuff();
}
private void beforeFinishDoThisStuff() {
sendBroadcastToMainActivity();
finish();
}
private void sendBroadcastToMainActivity() {
// create an intent and put your Receiver name as action name
// like you defined in your MainActivity
Intent intent = new Intent(MainActivity.MY_SUPER_INTERNAL_NOTIFICATION);
Bundle bundle = new Bundle();
// put whatever you want, here I put just the previous position of the object in the list
bundle.putInt(MY_EXAMPLE_KEY, myObjectPosition);
intent.putExtras(bundle);
// notify your MainActivity
LocalBroadcastManager
.getInstance(this)
.sendBroadcast(intent);
// after this finish !
}
}
Hope you understand how to notify activities with BroadcastManager. It's very powerful and simple to use.
Have fun coding !

putExtra doesn't seem to be working at all. Using ListView to get a string and using listView to display a string

I am programming a messaging app and I want to add users in a group. However, when a list of users pops up and I select one from the list, it doesn't pass the string (the username) to the other activity. All I get is an empty list.
Here is my code:
First Activity = Sending data (usernames from list) through putExtra()
public class ListUsersActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
private ProgressDialog progressDialog;
private BroadcastReceiver receiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_users);
Parse.initialize(this, "embpZ0spRUv5XwDgI23innll1sgHg0KZNiKzg6kl", "LPsU4UffPeqFXkQB1GfLCIJ4kvg20llPgbOnLise");
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, com.parse.ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
Intent goBackToAddPoolIntent = new Intent(ListUsersActivity.this, addNewPoolActivity.class);
addNewPoolActivity checker = new addNewPoolActivity();
checker.checkIfUserIsSelected(usersListView.getItemAtPosition(i).toString());
goBackToAddPoolIntent.putExtra("username", usersListView.getItemAtPosition(i).toString());
startActivity(goBackToAddPoolIntent);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
Second Activity = Receiving data from putExtra()
public class addNewPoolActivity extends Activity {
private static ArrayList<String> addedUsers;
private ArrayAdapter <String> addedUserAdapter;
private boolean userIsSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_pool);
Button addMembers = (Button) findViewById(R.id.bAddMembers);
addedUsers = new ArrayList<>();
//addedUsers.add("Group Members");
addMembers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showUsersToSelect = new Intent(addNewPoolActivity.this, ListUsersActivity.class);
startActivity(showUsersToSelect);
}
});
ListView addedUsersList = (ListView) findViewById(R.id.addedUsersListView);
addedUserAdapter = new ArrayAdapter<>(this, R.layout.user_list_item, addedUsers);
addedUsersList.setAdapter(addedUserAdapter);
if(userIsSelected){
Bundle extras = getIntent().getExtras();
addedUsers.add(extras.getString("username"));
}
}
public void checkIfUserIsSelected(String user){
if (user!=null){
userIsSelected = true;
}else{
userIsSelected = false;
}
}
Since the default value for a boolean is false, the code is never called because
if(userIsSelected){
will always evaluate to false since you have declared the varaible as
private boolean userIsSelected;
and the first snippet here is in onCreate() so it will only run the first time the Activity is created.
Maybe you are wanting to call checkIfUserIsSelected(someUser) before that code but without more context of what you hope to accomplish, it's hard to say.
Possibly, you want to use startActivityForResult() in some way?
In addition to #codeMagic 's answer (Since your boolean value is false, it won't call the statement that you are adding the new data). It's also because of you parse the Data "username" after you setAdapter of your ListView. So basically you are setting the data, and then trying to add the new data you parsed to the list. Either you need to do it before setting your data set to your adapter, or call addedUsersAdapter.notifyDataSetChanged() to refresh your listView's data set.
addedUserAdapter = new ArrayAdapter<>(this, R.layout.user_list_item, addedUsers);
addedUsersList.setAdapter(addedUserAdapter);
Bundle extras = getIntent().getExtras();
// Check if the username has been sent to this Activity.
if(extras != null && extras.containsKey("username")){
addedUsers.add(extras.getString("username"));
// Refresh Your Data Set
addedUserAdapter.notifyDataSetChanged();
}

Opening an activity with a webview (and url) restarts application

I am working on a small app that uses cursorloaders and loader callbacks. I am new to loader callbacks. The app displays a list of items and on item click a new activity is called that loads a url in a webview. I am not finishing the parent activity, but it so happens that when the webpage loads completely after some 1 or 2 minutes the previous activity restarts.
I did not know what to put in as the question since i am not sure if it the webpage that causes the restart of it the loader that causes the activity to restart. Though i have read the documentation and also:
this, but none of them talks about a restart.
I have also looked at this , but got no clue. Could this be a cause for the application restart ?
I am calling the following link in the webview activity:
url
I also looked at webview shows blank page, and from that i added the following code to mine (inside the webviewclient class)
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error){
handler.proceed() ;
}
------ EDIT, my activity extends SherlockFragmentActivity and implements LoaderCallbacks and my code is as under for the first activity
private ListView mListView;
private Cursor mCursor;
private MyListAdapter mListAdapter;
private CursorLoader mCursorLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView)findViewById(android.R.id.list);
fillDataIntoCursor();
new GetDataAsyncTask(this, mLimit).execute();
mListView.setOnItemClickListener(this);
}
private void fillDataIntoCursor() {
getLoaderManager().initLoader(0, null, this);
mListAdapter = new MyListAdapter(this,mCursor,false);
mListView.setAdapter(mListAdapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCursor = mListAdapter.getCursor();
mCursor.moveToPosition(position);
String link = mCursor.getString(mCursor.getColumnIndex(MyTable.COL_NAME_HERE));
Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
intent.putExtra("link",link);
startActivity(intent);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(mListAdapter!=null && cursor!=null)
mListAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursor) {
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
String[] projection = { // columns here};
mCursorLoader = new CursorLoader(this,
MyContentProvider.CONTENT_URI, projection, null, null, null);
return mCursorLoader;
}
Any help will be appreciated.
Thanks
PS: When i replace the url with Google the mainactivity does not restart. Also there are no conifg changes that take place which might cause the restart
I also get this error 10-09 21:02:53.229: E/InputDispatcher(156): channel '40bed3f0 packagename_here/packagename_here.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x8

rss feed into custom browser activity instead of normal browser

So I have my browser activity ready, however I'm struggling to get the code working to open the link from my rss feed to open in that, it just goes to a blank page. I have tried numerous things but nothing is working. So I have ended up going back to standard code as used in this tutorial http://www.itcuties.com/android/how-to-write-android-rss-parser/ . I am using the engadget feed as an example to see if i could get it working. Here is my listlistener activity
public class ListListener implements OnItemClickListener {
// List item's reference
List<RssItem> listItems;
// Calling activity reference
Activity activity;
public ListListener(List<RssItem> aListItems, Activity anActivity) {
listItems = aListItems;
activity = anActivity;
}
/**
* Start a browser with url from the rss item.
*/
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(listItems.get(pos).getLink()));
activity.startActivity(i);
}
}
and here is my engadgetfeed activity
public class EngadgetFeed extends Activity {
private EngadgetFeed local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_engadget_feed);
// Set reference to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
// Start download RSS task
task.execute("http://www.engadget.com/rss.xml");
// Debug the thread name
Log.d("Engadget", Thread.currentThread().getName());
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
// Debug the task thread name
Log.d("Engadget", Thread.currentThread().getName());
try {
// Create RSS reader
RssReader rssReader = new RssReader(urls[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("Engadget", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
// Get a ListView from main view
ListView endgadgetfeed = (ListView) findViewById(R.id.listMainView);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem> (local,R.layout.simple_list_item_1, result);
// Set list adapter for the ListView
endgadgetfeed.setAdapter(adapter);
// Set list view item click listener
endgadgetfeed.setOnItemClickListener(new ListListener(result, local));
}
}
}
any help would be appreciated
Well what I had to do, and i'm over the moon for answering my own question, is the following;
instead of having the following:
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(listItems.get(pos).getLink()));
activity.startActivity(i);
}
I used this:
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Uri uri;
String stringuri;
stringuri = (Uri.parse(listItems.get(pos).getLink())).toString();
Intent i = new Intent(activity, Browser2.class);
i.putExtra(EXTRA_MESSAGE, stringuri);
activity.startActivity(i);
}
So I hope this helps others who have the same.

Can't start activity from class

I am trying to start an activity from a normal class and I can't figure out how it is done, if it can be done. On an itemClick I want to start an activity that extends the ListView class to show a list of options.
Also the class that receives the onItemClick is not an activity. I will post the code to try to visualize what i mean.
This is my onClick method in the class that wants to start a an activity.
public void onClick(View v) {
if (v.equals(this)) {
notifyObservers(this.getId());
} else if(v.equals(editButton) || v.equals(deleteButton)) {
This is where I want to start the activity to show my ListView...
}
}
This is my class that extends the ListView class.
public class ProfileSettings extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] mainSettings = getResources().getStringArray(R.array.mainSettings);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mainSettings));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Do something
}
});
}
}
Thanks in advance!
I think this may help you:
"Pass the context of the activity via constructor to your class or make a static context in your activity.
With the context you can start activities like you would start them within the activity class."
class First extends Activity {
...
Second test = new Second(this);
test.start();
...
}
class Second {
private Context mContext;
...
public Second(Context c) { this.mContext = c; }
...
public start() { mContext.startActivity(...); }
}
for more detail check
http://www.anddev.org/view-layout-resource-problems-f27/starting-an-activity-from-a-non-activity-class-t14483.html
Try this in your onClick
Intent i = new Intent(this, ProfileSettings.class);
startActivity(i);
EDIT:
Also dont forget to add the activity to your manifest.

Categories

Resources