I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.
Related
I am trying to pass information from a text view into an ImageView to move the ImageView. The problem is I can't use the TextView information because it is defined as a TextView. So is there a way I can get it to use the TextView as an integer?
Do you mean you want to convert the text string in the textview to an integer? There's the java.lang.Integer class which has a static member parseInt() which might do what you need:
http://developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String)
Not completely sure what your looking for but if I read it right,
imageView.setMethod(parseInt(textView.getText()))
setMethod being which ever method your trying to set the int into.
I need the data from my accelerometer code which looks like so:
package com.bobhoil.tdodger;
import android.app.Activity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
public class TestActivity extends Activity implements SensorEventListener {
private TextView accelXValue;
private TextView accelYValue;
private TextView accelZValue;
private SensorManager sensorManager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.test);
accelXValue = (TextView) findViewById(R.id.accel_x_value);
accelYValue = (TextView) findViewById(R.id.accel_y_value);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
accelXValue.setText("0.00");
accelYValue.setText("0.00");
accelZValue.setText("0.00");
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelXValue.setText(Float.toString(sensorEvent.values[0]));
accelYValue.setText(Float.toString(sensorEvent.values[1]));
accelZValue.setText(Float.toString(sensorEvent.values[2]));
}
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
sensorManager.unregisterListener(this);
super.onStop();
}
}
Click to expand...
Click to collapse
I need to put that into my imageview and use scrollby to move the imageview around the screen.
I'm not too familiar with imageviews, are you using XMLs for the layout or creating the imageViews programmaticly? I'm assuming the textViews and imageViews are in seperate classes. Thus the easiest way to get the text from the textViews would be to first give them the "protected" token rather than "private" and reference them directly.
Code:
imageView.scrollBy(parseInt(TestActivity.accelXValue.getText()));
I have tried that before but no matter what I try I get an error. Here is the error:
Cannot make a static reference to the non-static field TestActivity.accelXValue
Click to expand...
Click to collapse
So then I change it to static and get the following error:
The method parseInt(CharSequence) is undefined for the type TestActivity
Click to expand...
Click to collapse
I can't seem to get something that seems so simple to work.
Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Pouya_am said:
Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Click to expand...
Click to collapse
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
SimplicityApks said:
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
Click to expand...
Click to collapse
Yeah you're right , I just want to use the drawer in order to change contents.
So as you suggest , I just have to use a simple tricks to make the drawer enable in desire Fragment.
I don't want to , I am asked to make it possible....
I have been trying to implement the broadcast receiver programatically , but my unregister method is not working or the app is working even if it in killed state .What i'm trying to accomplish is to display a test message ,when a sms receives ,,i have two buttons in app,register and unregister .If the user presses register ,no matter whether the app is running foreground or background the app should display the toast message,but if i press unregister the app should not invoke toast message .The code is
Code:
package gates.apps.automaticmessageresponder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
SmsReceiver broadcastReceiver=new SmsReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void register(View view){
this.registerReceiver(broadcastReceiver, new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED"));
Log.e("register","pressed");
}
public void unRegister(View view){
this.unregisterReceiver(broadcastReceiver);
Log.e("unregister","pressed");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and another class is
Code:
package gates.apps.automaticmessageresponder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
i have not modified the manifest ,except adding sms recieve permission
But the problem with above code is ,even i don't press register it's getting invoked and even if i press unregister button ,it's not stopping
Dude you haven't added a listener for on click(unless you have specified register in layout for button). Nor can I see the button defined. Plus your toast message falls in try catch block. So look for clues in that. I think it'll work once you correct the code. I'll help more if its possible.
Please give a thanks if you think this post helped you!
Sent from my Nexus 4 using XDA Premium 4 Mobile App .
Hi, for the past hour or so, i have been trying to fix a problem and that problem is with the edit text part of my music player app...
Basically i have added a search function (EditText) to the music list of my app to allow people to search the songs from the list and then play the song, but it doesn't work, it just plays the wrong file when you click on it.
Now if you go to play a song without using the search then it'll work perfectly
Now as far as i can gather, it has something to do with the ' in.putExtra("songPath", songIndex); ' part of the click method, which again works perfectly fine when using the OnItemClick method but doesn't with the searches OnClick method
So that's where i need help... HOW DO I SEND THE FILES DATA PATH TO THE MUSIC PLAYER?
Here's the songs list activity which contains both the search and standard ListView:
Code:
import java.util.ArrayList;
import java.util.HashMap;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.simplistic.simplisticmusicfree.R;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class PlayListActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String,String>> songsList = new ArrayList<HashMap<String, String>>();
ListView musiclist;
Cursor mCursor;
int songTitle;
int count;
int songPath;
EditText songResult;
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList(this);
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
final ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle", "songAlbum" }, new int[] {
R.id.songTitle, R.id.songAlbum});
setListAdapter(adapter);
final EditText songResult = (EditText) findViewById(R.id.inputSearch);
songResult.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
int songIndex = 0;
// Sending songIndex to PlayerActivity
in.putExtra("songPath", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
songResult.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
((Filterable) adapter).getFilter().filter(s);
}
});
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("songPath", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
}
and here's the OnClicks result code:
Code:
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songPath");
// play selected song
playSong(currentSongIndex);
}
}
public void playSong(int songIndex){
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
shuffle();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.img_btn_pause2);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
So yeah any solution would be grateful!
Thanks
I have coded this android app which produces a listView containing songs which are streamed from the internet, and the user can play them by clicking them using the mediaPlayer.
What i am having trouble with is allowing the user to add a song to the arrayList that populates the ListView within MainActivity.java. I have used the settings page to add textboxes so the user can add their songs by inputting, Song Name, Artist and the Direct Link to the song. Though the code i have used for this doesn't work, it should add the Song Name, Artist and Direct Link into the array_list_music ArrayList, then update the ListView, or at least i think that is how it should be done, although after entering details and clicking the 'Add Song' button, and returning to the main page, the ListView does not that the newly added song.
I have shown my code below.
So if someone could help with this problem, that would be great, thanks.
MainActivity.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
public class MainActivity extends ListActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private ListView list;
public MainArrayAdapter adapter;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
ArrayList<String> array_list_music = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = getListView();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
//ArrayList<String> array_list_music = new ArrayList<String>();
//Used to add a song to the array list
array_list_music
.add("Jar of Hearts"
+ " ### "
+ "Christina Perri"
+ " ### "
+ "LINK");
array_list_music
.add("Save The World"
+ " ### "
+ "Swedish House Mafia feat. John Martin"
+ " ### "
+ "LINK");
array_list_music
.add("Bromance"
+ " ### "
+ "Avicii"
+ " ### "
+ "LINK");
adapter = new MainArrayAdapter(MainActivity.this, array_list_music);
setListAdapter(adapter);
//used to display toast and to play song using the URL, when clicking on a song
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Object item = getListView().getItemAtPosition(arg2);
String the_list_item = item.toString();
Toast.makeText(MainActivity.this, "You are now listening to: " + the_list_item, Toast.LENGTH_LONG).show();
String[] aux = the_list_item.split(" ### ");
String url_to_play = aux[2];
playAudio(url_to_play);//sends url from arraylist item to the playAudio method
}
});
}
//used to play audio using the android mediaPlayer
private void playAudio(String url_to_play) {
//stop & reset player
try {
mediaPlayer.stop();
mediaPlayer.reset();
} catch (Exception e) {
}
//set the url, prepare it, and then play it
try {
mediaPlayer.setDataSource(url_to_play);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e(TAG, "Could not open file " + url_to_play + ".", e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i_settings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i_settings);
break;
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
//used to hide media controller, stop the media player and to release the url.
@Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
@Override
public void pause() {
mediaPlayer.pause();
}
@Override
public void seekTo(int arg0) {
mediaPlayer.seekTo(arg0);
}
@Override
public void start() {
mediaPlayer.start();
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(list);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
//------- what can you do from here -------
// implement your own media player with buttons since this one is not behaving "smart"..
// make next,previous buttons
// highlight the list item on click
// add your own server for playing music
// anything you want :)
}
MainArrayAdapter.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.groupassignment.musicplayer.R;
public class MainArrayAdapter extends ArrayAdapter<String> implements ListAdapter {
private final Context context;
private ArrayList<String> data_array;
private List<DataSetObserver> observers = new LinkedList<DataSetObserver>();
public MainArrayAdapter(Context context, ArrayList<String> list_of_ids) {
super(context, R.layout.main_list_rowlayout, list_of_ids);
this.context = context;
this.data_array = list_of_ids;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_list_rowlayout, parent,
false);
TextView textView_main_row_song_name = (TextView) rowView
.findViewById(R.id.textView_main_row_song_name);
TextView textView_main_row_singer_name = (TextView) rowView
.findViewById(R.id.textView_main_row_singer_name);
try {
String[] aux = data_array.get(position).split(" ### ");
String song_name = aux[0];
String artist = aux[1];
String url = aux[2];
textView_main_row_song_name.setText(song_name);
textView_main_row_singer_name.setText(artist);
} catch (Exception e) {
// TODO: handle exception
}
return rowView;
}
public void setArray(ArrayList<String> data_array){
this.data_array = data_array;
for (DataSetObserver observer : observers){
observer.onChanged();
}
}
@Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
((LinkedList) observers).addFirst(dataSetObserver);
}
@Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
observers.remove(dataSetObserver);
}
}
SettingsActivity.java
Code:
package com.groupassignment.musicplayer;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import com.groupassignment.musicplayer.R;
public class SettingsActivity extends Activity {
public String str ="";
String songName;
String artist;
String directLink;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
songName = ((EditText)findViewById(R.id.editTextSongName)).toString();
artist = ((EditText)findViewById(R.id.editTextArtist)).toString();
directLink = ((EditText)findViewById(R.id.editTextDirectLink)).toString();
};
public void buttonAddSongClicked(View v)
{
addSong(songName, artist, directLink);
}
private void addSong(String artist, String songName, String directLink)
{
MainActivity main = new MainActivity();
main.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
main.adapter.notifyDataSetChanged();
main.adapter = new MainArrayAdapter(main, main.array_list_music);
}
}
The problem is that you create new instances of adapter each time, instead of updating the existing one. Easy way to solve your problem is to change attributes of array_list_music and adapter to public static in your MainActivity and modify addSong inside SettingsActivity to:
Code:
private void addSong(String artist, String songName, String directLink)
{
MainActivity.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
MainActivity.adapter.notifyDataSetChanged();
}