MediaMetaDataRetriever.setDataSource return null - java

I'm trying to develop an application (Radio Stream) app, I want to get the details of the song that is playing on the radio for that MediaMetadataRetriever API but when i set my URL i get this error :
java.lang.IllegalArgumentException
at
android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:71)
at
maa.myapp.MainActivity$PlayerTask.onPostExecute(MainActivity.java:447)
at
maa.myapp.MainActivity$PlayerTask.onPostExecute(MainActivity.java:419)
this my code :
MediaPlayer mediaPlayer;
String stream = "https://plaza.one/mp3";
boolean prepared =false;
boolean started =false ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
new PlayerTask().execute(stream);
}
public class PlayerTask extends AsyncTask<String,Void,Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(strings[0]);
prepared=true;
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
/*get details : */
MediaMetadataRetriever mMediaMetaDataRetriever = new MediaMetadataRetriever();
mMediaMetaDataRetriever.setDataSource(stream,new HashMap<String, String>());
String titleName = mMediaMetaDataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
Toast.makeText(MainActivity.this, "Title : "+titleName, Toast.LENGTH_SHORT).show();
}
}
}

finally it work with 'com.vodyasov:amr:0.5' library
Uri uri = Uri.parse(stream);
OnNewMetadataListener listener = new OnNewMetadataListener() {
#Override
public void onNewHeaders(String stringUri, List<String> name, List<String> desc, List<String> br, List<String> genre, List<String> info) {}
#Override
public void onNewStreamTitle(String stringUri, String streamTitle) {
songinfo.setText("Song Name : "+streamTitle);
}
};
AudiostreamMetadataManager.getInstance()
.setUri(uri)
.setOnNewMetadataListener(listener)
.setUserAgent(UserAgent.WINDOWS_MEDIA_PLAYER)
.start();

Try this:
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14){
mmr.setDataSource(stream, new HashMap<String, String>());
}else {
mmr.setDataSource(stream);
}
String titleName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));
Toast.makeText(MainActivity.this, "Title : "+titleName, Toast.LENGTH_SHORT).show();
}
If that doesn't work then you should make sure that the link you are using actually returns a file.
Try doing the above inside onCreate, the problem could be something with your AsyncTask.

Related

How to call the Mainactivity method in Asynctask for background work?

I want a method (present in MainActivity) to call from the doInBackground(File... file) method of MyAsynctask class (present in MainActivity) and that method have to work in background also because it is time taking and my app stops working for a moment and there is no any dialog appearing which I have called in onPreExecute() method how to solve the problem here is my code it is working very fine but taking too much time and my app looks hanged but it is not actually.
ArrayList<HashMap<String,String>> getPlayList(File rootFolder) {
ArrayList<HashMap<String,String>> fileList = new ArrayList<>();
try {
File[] files = rootFolder.listFiles();
//here you will get NPE if directory doesn't contains any file,handle it like this.
if (files != null) {
for (File file : files) {
if (file.isDirectory() && !file.isHidden()) {
if (true) {
fileList.addAll(getPlayList(file));
}
else {
break;
}
} else if (file.getName().endsWith(".pdf")) {
HashMap<String, String> song = new HashMap<>();
song.put("file_path", file.getAbsolutePath());
song.put("file_name", file.getName());
fileList.add(song);
}
}
}
return fileList;
} catch (Exception e) {
return null;
}
}
And Asynctask class is below..
private class AsyncTaskExample extends AsyncTask<File, String, ArrayList> {
#Override
protected ArrayList doInBackground(File... file) {
ArrayList<HashMap<String,String>> songList=getPlayList(folder);
if(songList!=null){
for(int i=0;i<songList.size();i++){
final String fileName=songList.get(i).get("file_name");
final String filePath=songList.get(i).get("file_path");
//saving filePath and filName in SQLite Database..
saveFileToDatabase(filePath, fileName);
}
}
return songList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("Please wait...Loading..");
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
}
#Override
protected void onPostExecute(ArrayList arrayList) {
super.onPostExecute(arrayList);
if (mFiles != null)
{
p.dismiss();
}
else
{
p.show();
}
}
}
How to do the work efficiently?
Solution
And the problem was these lines of code given below:
AsyncTaskExample taskExample = new AsyncTaskExample();
folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
//I was writing this below line..
taskExample.doInBackground(folder);
//but it should be like in line below..
taskExample.execute(folder);
I would suggest you to define a callback, and pass it through in your asynctask's constructor so you can notify your main activity to show the dialog whenever it's needed.
Callback
public interface AsyncTaskExampleCallback {
public void onShowDialog();
public void onHideDialog();
}
Async task
class AsyncTaskExample extends AsyncTask<File, String, ArrayList> {
#Nullable
private AsyncTaskExampleCallback callback = null;
public AsyncTaskExample(#NotNull AsyncTaskExampleCallback callback) {
this.callback = callback;
}
#Override
protected ArrayList doInBackground(File... file) {
ArrayList<HashMap<String, String>> songList = getPlayList(folder);
if (songList != null) {
for (int i = 0; i < songList.size(); i++) {
final String fileName = songList.get(i).get("file_name");
final String filePath = songList.get(i).get("file_path");
//saving filePath and filName in SQLite Database..
saveFileToDatabase(filePath, fileName);
}
}
return songList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (callback != null) {
callback.onShowDialog();
}
}
#Override
protected void onPostExecute(ArrayList arrayList) {
super.onPostExecute(arrayList);
if (mFiles != null) {
if (callback != null) {
callback.onHideDialog();
}
} else {
if (callback != null) {
callback.onShowDialog();
}
}
}
}
Main Activity
public class MainActivity extends AppCompatActivity implements AsyncTaskExampleCallback {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncTaskExample(this).execute();
}
#Override
public void onShowDialog() {
//Show dialog here
}
#Override
public void onHideDialog() {
//Hide dialog here
}
}

Stop/start mediaplayer from another activity

i'm trying to play stream radio using Mediaplayer with MP1 as variable of Mediaplayer i want to play it in all Fragments app,expect one activity (ActivityOne) which is contains another Mediaplayer MP2 to play,so i want to stop MP1 when i'm in (ActivityOne) activity, and play MP2 , and when i return from (ActivityOne) i want to resume MP1, my big problem is the (ActivityOne) called when i click button which is exist in fragment
my code below works only in one direction :
when i return from (ActivityOne) activity, the music stops.
structure of the app : MainAcitivty > Fragment > ActivityOne
MainActivity.java
MediaPlayer MP1;
boolean prepared = false;
boolean started = false;
PlayerTask playerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(stream);
/**/
MusicButton = findViewById(R.id.toggleButton);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (started && MusicButton.isChecked()) {
started = false;
MP1.pause();
MusicButton.setChecked(true);
} else {
started = true;
MP1.start();
MusicButton.setChecked(false);
}
}
});
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar loadingRL = findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP1.setAudioAttributes(attribs);
} else {
MP1.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
MP1.setDataSource(strings[0]);
MP1.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP1) {
MP1.start();
}
});
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
loadingRL.setVisibility(View.VISIBLE);
}
ActivityOne.java
MediaPlayer MP2;
boolean prepared = false;
boolean started = false;
ToggleButton music;
PlayerTask playerTask = null;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
coordinatorLayout = findViewById(R.id.coord);
MP2 = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP2.setAudioAttributes(attribs);
} else {
MP2.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
#Override
protected Boolean doInBackground(String... strings) {
if (!isCancelled()) {
try {
MP2.setDataSource(strings[0]);
MP2.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP2) {
MP2.start();
}
});
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
all.setVisibility(View.VISIBLE);
}
#Override
protected void onCancelled(Boolean aBoolean) {
if (isCancelled() && MP2.isPlaying()) {
MP2.stop();
}
}
}
#Override
public void onBackPressed() {
if (playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (MP2.isPlaying()) {
MP2.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
playerTask.cancel(true);
}
super.onBackPressed();
}
i spent 2 days to resolve this problem without any result ,please someone help me i will be thankful to him
You could solve this by using Otto library. First create a new Java class but choose enum instead and inside enum you can add: PLAY and PAUSE for example:
public enum PlaybackEvent {
PLAY, PAUSE
}
Then if you are not using custom Application class create one and extend Application and override inside onCreate method. Inside your app gradle add compile 'com.squareup:otto:1.3.8' then create an instance of Bus inside Application class and register. For example this would look like this:
public class MApplication extends Application {
public static Bus sBus = new Bus(ThreadEnforcer.MAIN);
#Override
public void onCreate() {
super.onCreate();
sBus.register(this);
}
Don't forget to replace in manifest default application class with your new one
<application
android:name="com.packagename.MApplication"
After that in your MainActivity class override and register/unregister your event bus in onResume and in onPause.
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
}
catch(Exception e){
e.printStackTrace();
}
}
After that in MainActivity create a public void method passing as parameter PlayBackEvent and Subscribe so you can listen a message which will be send from your fragment class. For example:
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PLAY:
if(MP1.isPlaying())
MP1.pause();
break;
case PAUSE:
if(!MP1.isPlaying())
MP1.play();
break;
}
}
And last thing you have to do is to send the message from your fragment when starting second activity and that will go:
MApplication.sBus.post(PlaybackEvent.PAUSE);
and of course you can also send a message to play again MP1 from second activity overriding onBackPressed putting inside line of code:
MApplication.sBus.post(PlaybackEvent.PLAY);
Hope this will help you to resolve the problem.
Have you tried using startActivityForResult()?

How to add Images with Picasso

I'm trying to add images to my listview, which is made from content retrieved from json. For the purpose of adding the images I'm trying to use picasso, and I've watched a tutorial about it and it worked, the problem is that I don't think it can be used in my app, at least not with the method I saw.
Here's my code, hope anyone can help me and explain me how to do this.
public class TodosOsPaises extends AppCompatActivity {
private String TAG = TodosOsPaises.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://";
ArrayList<HashMap<String, String>> listaPaises;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todos_os_paises);
listaPaises = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPaises().execute();
}
private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TodosOsPaises.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String Coord_LAT = jsonObject1.getString("Coord_LAT");
String Coord_LONG = jsonObject1.getString("Coord_LONG");
String Coord_Zoom = jsonObject1.getString("Coord_Zoom");
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
pais.put("Coord_LAT", Coord_LAT);
pais.put("Coord_LONG", Coord_LONG);
pais.put("Coord_Zoom", Coord_Zoom);
listaPaises.add(pais);
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(TodosOsPaises.this, listaPaises, R.layout.list_item, new String[]{"Designacao", "URL_IMAGEM"},
new int[]{R.id.Designacao, R.id.imageViewPais});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
Intent intent = new Intent(TodosOsPaises.this, MapsActivity.class);
intent.putExtra("data", listaPaises.get(position));
startActivity(intent);
}
});
Collections.sort(listaPaises, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> first, HashMap<String, String> second) {
String firstValue = first.get("Designacao");
String secondValue = second.get("Designacao");
return firstValue.compareTo(secondValue);
}
});
}
}
}
Picasso.with(content)
.load("path_or_url_or_file")
.into(new Target() {
#Override public void onBitmapLoaded(final Bitmap bitmap,
final Picasso.LoadedFrom from) {
}
#Override public void onBitmapFailed(final Drawable errorDrawable) {
}
#Override public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});

how to change AsyncTask to #background and #UiThread

Can anyone help me a bit to change AsyncTask to #Background and #UiThread?
How should I start? What should I delete?
onPost and onPre should be converted to UiThread?
I will be very grateful for advice
Here is piece of my code.
#Click
void button1(View view)
{
ReadPic rp = new ReadPic();
rp.execute();
}
class ReadPic extends AsyncTask<Void, Void, Void>
{
ProgressBar progressBar;
boolean sukces = true;
public ReadPic()
{
progressBar = new ProgressBar(getBaseContext());
}
#Override
protected Void doInBackground(Void... arg0)
{
URL u;
InputStream is;
try
{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
}
catch( Exception e)
{
sukces = false;
}
return null;
}
#Override
protected void onPreExecute()
{
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
textView1.setText("DOWNLOADING...");
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result)
{
if(sukces)
{
imageView.setImageBitmap(bmp);
imageView1.setImageBitmap(bmp);
imageView2.setImageBitmap(bmp);
imageView3.setImageBitmap(bmp);
imageView4.setImageBitmap(bmp);
imageView5.setImageBitmap(bmp);
imageView6.setImageBitmap(bmp);
imageView7.setImageBitmap(bmp);
imageView8.setImageBitmap(bmp);
textView1.setText("Downloading finished");
}
else
{
textView1.setText("Error when downloading");
}
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
super.onPostExecute(result);
}
You can convert it like this:
#Click
void button1(View view) {
startProcess();
}
void startProcess() {
if(progressBar !=null) // progressBar should be a field in your Activity / Fragment
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
textView1.setText("DOWNLOADING...");
yourBackgroundMethod();
}
#Background
void yourBackgroundMethod() {
URL u;
InputStream is;
try
{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
onBackgroundSuccess();
onBackgroundTerminate();
}
catch( Exception e)
{
onBackgroundError();
onBackgroundTerminate();
}
}
#UiThread
void onBackgroundError() {
imageView.setImageBitmap(bmp);
imageView1.setImageBitmap(bmp);
imageView2.setImageBitmap(bmp);
imageView3.setImageBitmap(bmp);
imageView4.setImageBitmap(bmp);
imageView5.setImageBitmap(bmp);
imageView6.setImageBitmap(bmp);
imageView7.setImageBitmap(bmp);
imageView8.setImageBitmap(bmp);
textView1.setText("Downloading finished");
}
#UiThread
void onBackgroundSuccess() {
textView1.setText("Error when downloading");
}
#UiThread
void onBackgroundTerminate() {
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
}

How to add asyncTask code in application?

I have a register activity in my application. This has inputs of userid,email,password and mobile no. I have created an UI.
code:
public class RegisterActivity extends AppCompatActivity {
TextView already;
Button signUp;
RelativeLayout parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
parent = (RelativeLayout)findViewById(R.id.parentPanel);
setupUI(parent);
already = (TextView)findViewById(R.id.alreadyRegistered);
signUp = (Button) findViewById(R.id.sign_up_button);
already.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(RegisterActivity.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
Now I want to sync this UI with server.
For this I have a code of asyncTask created in another activity. How can I call this code or implement this code with UI?
AsyncTask code : RegisterActivity
public class RegisterActivity extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
context = this;
RegisterAsyncTask task = new RegisterAsyncTask();
String userPhoto = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlLBAIHAGdIMrN7hH1jKkmZz+d7MPu15md6PtCyrHmqvsgNVjY7Djh69OgwEaU1pkVwanKK0NLSsgvA8Vk=";
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
}
public class RegisterAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "api/user/register.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("result");
String message = jsonObject.getString("message");
if ( result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code when api fails goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
How can I sync this? Please help. Thank you.
EDIT:
getEventsAsyncTask:
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog :
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog want to show events from asyncTask. Thank you.
Not sure if i understand your question correctly, but to execute the AsyncTask, you just have to create an instance of RegisterAsyncTask and call the execute() method on it.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(yourMap);
// you can pass multiple params to the execute() method
Or, if you don't need to get ahold of the instance:
new RegisterAsyncTask().execute(yourMap);
You can simply put your hashmap object, alongwith AsyncTask in your login activity code, and simply call AsyncTask in following manner.
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
//call asynctask like this.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(params);

Categories

Resources