I twice get anr when i swipe the app from recent activities. And then the app works fine also I get an anr when I switch to landscape mode. The app works as expected as long as it is not oriented landscape or swiped from recent apps.
Can someone point out what I am doing wrong here.
Thanks
MyService.java:
public class MyService extends Service {
public static boolean started = false;
public static String TRANSACTION_DONE = "com.example.root.project";
private WebSocketClient client = null;
public static SQLiteDatabase myDataBase = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if(started){
String message = intent.getStringExtra("message");
if(client != null){
client.send(message);
}
}
if (!started) {
myDataBase = openOrCreateDatabase("Messages.db", MODE_PRIVATE, null);
myDataBase.execSQL("CREATE TABLE IF NOT EXISTS messages " +
"(tag TEXT primary key, message TEXT);");
started = true;
URI uri = null;
try {
uri = new URI(intent.getStringExtra("ip"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
client = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.accumulate("addme",intent.getStringExtra("name"));
} catch (JSONException e) {
e.printStackTrace();
}
client.send(jsonObject.toString());
}
#Override
public void onMessage(String message) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(message);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonObject.has("resolve")) {
PendingIntent notificIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class), 0);
// Builds a notification
NotificationCompat.Builder mBuilder =
null;
try {
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.add)
.setContentTitle(jsonObject.getString("name"))
.setTicker(jsonObject.getString("resolve"))
.setContentText(jsonObject.getString("destination"));
} catch (JSONException e) {
e.printStackTrace();
}
// Defines the Intent to fire when the notification is clicked
mBuilder.setContentIntent(notificIntent);
// Set the default notification option
// DEFAULT_SOUND : Make sound
// DEFAULT_VIBRATE : Vibrate
// DEFAULT_LIGHTS : Use the default light notification
mBuilder.setDefaults(Notification.DEFAULT_ALL);
// Auto cancels the notification when clicked on in the task bar
mBuilder.setAutoCancel(true);
// Gets a NotificationManager which is used to notify the user of the background event
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
// Post the notification
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
} else if (jsonObject.has("remove")) {
try {
String tag = jsonObject.getString("remove");
myDataBase.execSQL("DELETE FROM messages WHERE tag = " + tag + ";");
} catch (JSONException e) {
e.printStackTrace();
}
if (isForeground(TRANSACTION_DONE)) {
Intent broadcast = new Intent(TRANSACTION_DONE);
broadcast.putExtra("message", message);
sendBroadcast(broadcast);
}
} else {
try {
myDataBase.execSQL("INSERT INTO messages (tag, message) VALUES ('" +
jsonObject.getString("tag") + "', '" + message + "');");
} catch (JSONException e) {
e.printStackTrace();
}
if (isForeground(TRANSACTION_DONE)) {
Intent broadcast = new Intent(TRANSACTION_DONE);
broadcast.putExtra("message", message);
sendBroadcast(broadcast);
}
}
}
#Override
public void onClose(int i, String s, boolean b) {
Log.d("myTag", "onClose: websocket closing ");
Toast.makeText(getApplicationContext(),"closing websocket",Toast.LENGTH_LONG).show();
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
client.connect();
}
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Toast.makeText(getApplicationContext(),"closing client",Toast.LENGTH_LONG).show();
client.close();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("myTag", "onDestroy: service being destroyed ");
try {
client.closeBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast.makeText(this,"Service is closing on destroy called",Toast.LENGTH_LONG).show();
}
public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private String name;
private String ip;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog_layout, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.dialogTitle);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogDesc);
String title = editText.getText().toString().trim();
String desc = editText2.getText().toString().trim();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("title", title);
jsonObject.accumulate("desc", desc);
jsonObject.accumulate("name",name);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",jsonObject.toString());
startService(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(MyPreferences.isFirst(this)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.login_dialog, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.dialogName);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogIp);
name = editText.getText().toString().trim();
ip = editText2.getText().toString().trim();
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("name", name);
intent.putExtra("ip", ip);
MainActivity.this.getSharedPreferences("my_preferences",MODE_PRIVATE).edit().putString("name",name).putString("ip",ip).commit();
startService(intent);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new CustomAdapter(MainActivity.this);
listView.setAdapter(adapter);
IntentFilter filter = new IntentFilter();
filter.addAction(MyService.TRANSACTION_DONE);
registerReceiver(myReceiver, filter);
new Handler().post(new Runnable() {
#Override
public void run() {
if (MyService.myDataBase == null) return;
Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
int messageColumn = cursor.getColumnIndex("message");
cursor.moveToFirst();
if (cursor != null && (cursor.getCount() > 0)) {
do {
String message = cursor.getString(messageColumn);
try {
JSONObject jsonObject = new JSONObject(message);
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
adapter.update();
}
}
});
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}else {
Intent intent = new Intent(this, MyService.class);
name = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("name","no_name");
ip = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("ip","no_ip");
intent.putExtra("name",name);
intent.putExtra("ip",ip);
startService(intent);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new CustomAdapter(this);
listView.setAdapter(adapter);
IntentFilter filter = new IntentFilter();
filter.addAction(MyService.TRANSACTION_DONE);
registerReceiver(myReceiver, filter);
new Handler().post(new Runnable() {
#Override
public void run() {
if (MyService.myDataBase == null) return;
Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
int messageColumn = cursor.getColumnIndex("message");
cursor.moveToFirst();
if (cursor != null && (cursor.getCount() > 0)) {
do {
String message = cursor.getString(messageColumn);
try {
JSONObject jsonObject = new JSONObject(message);
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
adapter.update();
}
}
});
}
}
#Override
protected void onDestroy() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onDestroy();
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(message);
if(jsonObject.has("remove")){
adapter.remove(jsonObject.getString("remove"));
adapter.update();
}else {
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
adapter.update();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<ListViewData> objects;
public void add(String title, String desc, String tag) {
objects.add(new ListViewData(title, desc, tag));
}
public void remove(String tag){
for(ListViewData data : objects){
if(data.getTag().equals(tag)){
objects.remove(data);
break;
}
}
}
public void update(){
notifyDataSetChanged();
}
private class ViewHolder {
TextView title;
TextView description;
Button resolve;
Button subscribe;
Button unSubscribe;
}
public CustomAdapter(Context context) {
inflater = LayoutInflater.from(context);
objects = new ArrayList<>();
}
public int getCount() {
return objects.size();
}
public ListViewData getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_list_layout, null);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.description = (TextView) convertView.findViewById(R.id.desc);
holder.resolve = (Button) convertView.findViewById(R.id.resolve);
holder.subscribe = (Button) convertView.findViewById(R.id.subscribe);
holder.unSubscribe = (Button) convertView.findViewById(R.id.unsubscribe);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(objects.get(position).getTitle());
holder.description.setText(objects.get(position).getDescription());
holder.resolve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.name);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.destination);
String name = editText.getText().toString().trim();
String destination = editText2.getText().toString().trim();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("name", name);
jsonObject.accumulate("destination", destination);
jsonObject.accumulate("resolve",objects.get(position).getTag());
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",jsonObject.toString());
startService(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
holder.subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag = objects.get(position).getTag();
try {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",new JSONObject().accumulate("subscribe",tag).accumulate("name",name).toString());
startService(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
holder.unSubscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag = objects.get(position).getTag();
try {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",new JSONObject().accumulate("unsubscribe",tag).accumulate("name",name).toString());
startService(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return convertView;
}
}
}
class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
Related
So I have an app which plays media in ExoPlayer2 but now I wanted to add a button which can open the same video in an external player.
I am actually not getting what to add in intent so help is required.
Here's the open in external button option I'm trying to add:
imgPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(), "video/*");
startActivity(Intent.createChooser(intent, "Complete action using"));
}
});
Now the issue is, idk what to add in Uri.parse(), I want the currently playing video to be played in an external player.
Thanks in advance.
Edit:
My Activity Class:
public class DetailsActivity extends AppCompatActivity {
int i = 0;
private TextView tvName,tvDirector,tvRelease,tvCast,tvDes,tvGenre,tvRelated;
private RecyclerView rvDirector,rvServer,rvRelated,rvComment;
public static RelativeLayout lPlay;
private EpisodeAdapter episodeAdapter;
private HomePageAdapter relatedAdapter;
private LiveTvHomeAdapter relatedTvAdapter;
public static LinearLayout llBottom,llBottomParent,llcomment;
private SwipeRefreshLayout swipeRefreshLayout;
private String type="",id="";
private ImageView imgAddFav;
public static ImageView imgBack;
public static ImageView imgPlayer;
private String V_URL = "";
public static WebView webView;
public static ProgressBar progressBar;
private boolean isFav = false;
private ShimmerFrameLayout shimmerFrameLayout;
private Button btnComment;
private EditText etComment;
private CommentsAdapter commentsAdapter;
private String commentURl;
private AdView adView;
private InterstitialAd mInterstitialAd;
public static SimpleExoPlayer player;
public static PlayerView simpleExoPlayerView;
public static SubtitleView subtitleView;
public static ImageView imgFull;
public static ImageView imgfit;
public static boolean isPlaying,isFullScr;
public static View playerLayout;
private int playerHeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
llBottom=findViewById(R.id.llbottom);
swipeRefreshLayout=findViewById(R.id.swipe_layout);
imgAddFav=findViewById(R.id.add_fav);
imgBack=findViewById(R.id.img_back);
webView=findViewById(R.id.webView);
progressBar=findViewById(R.id.progressBar);
llBottomParent=findViewById(R.id.llbottomparent);
lPlay=findViewById(R.id.play);
rvRelated=findViewById(R.id.rv_related);
tvRelated=findViewById(R.id.tv_related);
shimmerFrameLayout=findViewById(R.id.shimmer_view_container);
simpleExoPlayerView = findViewById(R.id.video_view);
subtitleView=findViewById(R.id.subtitle);
playerLayout=findViewById(R.id.player_layout);
imgFull=findViewById(R.id.img_full_scr);
imgfit=findViewById(R.id.fit);
rvServer=findViewById(R.id.rv_server_list);
imgPlayer=findViewById(R.id.img_player);
shimmerFrameLayout.startShimmer();
playerHeight = lPlay.getLayoutParams().height;
progressBar.setMax(100); // 100 maximum value for the progress value
progressBar.setProgress(50);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
imgBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
imgPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
startActivity(Intent.createChooser(intent, "Complete action using"));
}
});
type = getIntent().getStringExtra("vType");
id = getIntent().getStringExtra("id");
final SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
if (preferences.getBoolean("status",false)){
imgAddFav.setVisibility(VISIBLE);
}else {
imgAddFav.setVisibility(GONE);
}
imgFull.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFullScr){
isFullScr=false;
showSystemUI();
llBottomParent.setVisibility(VISIBLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
lPlay.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, playerHeight));
imgfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
}
});
}else {
hideSystemUI();
isFullScr=true;
llBottomParent.setVisibility(GONE);
lPlay.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
imgfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
Runnable r = new Runnable() {
#Override
public void run() {
i = 0;
}
};
if (i == 1) {
//Single click
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
} else if (i == 2) {
//Double click
i = 0;
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
} else if (i == 3) {
// Triple Click
i = 0;
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
} else if (i == 4) {
// Fourth Click
i = 0;
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
}
}
});
}
}
});
imgAddFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = new ApiResources().getAddFav()+"&&user_id="+preferences.getString("id","0")+"&&videos_id="+id;
if (isFav){
String removeURL = new ApiResources().getRemoveFav()+"&&user_id="+preferences.getString("id","0")+"&&videos_id="+id;
removeFromFav(removeURL);
}else {
addToFav(url);
}
}
});
if (!isNetworkAvailable()){
new ToastMsg(DetailsActivity.this).toastIconError(getString(R.string.no_internet));
}
initGetData();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initGetData();
}
});
}
private void initGetData(){
if (!type.equals("tv")){
//----related rv----------
relatedAdapter=new HomePageAdapter(this,listRelated);
rvRelated.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvRelated.setHasFixedSize(true);
rvRelated.setAdapter(relatedAdapter);
if (type.equals("tvseries")){
rvRelated.removeAllViews();
listRelated.clear();
rvServer.removeAllViews();
listDirector.clear();
listEpisode.clear();
episodeAdapter=new EpisodeAdapter(this,listDirector);
rvServer.setLayoutManager(new LinearLayoutManager(this));
rvServer.setHasFixedSize(true);
rvServer.setAdapter(episodeAdapter);
getSeriesData(type,id);
}else {
rvServer.removeAllViews();
listDirector.clear();
rvRelated.removeAllViews();
listRelated.clear();
serverApater=new ServerApater(this,listDirector);
rvServer.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvServer.setHasFixedSize(true);
rvServer.setAdapter(serverApater);
getData(type,id);
final ServerApater.OriginalViewHolder[] viewHolder = {null};
serverApater.setOnItemClickListener(new ServerApater.OnItemClickListener() {
#Override
public void onItemClick(View view, CommonModels obj, int position, ServerApater.OriginalViewHolder holder) {
iniMoviePlayer(obj.getStremURL(),obj.getServerType(),DetailsActivity.this);
serverApater.chanColor(viewHolder[0],position);
holder.name.setTextColor(getResources().getColor(R.color.colorPrimary));
viewHolder[0] =holder;
}
});
}
SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
String url = new ApiResources().getFavStatusURl()+"&&user_id="+sharedPreferences.getString("id","0")+"&&videos_id="+id;
if (sharedPreferences.getBoolean("status",false)){
getFavStatus(url);
}
}else {
llcomment.setVisibility(GONE);
tvRelated.setText("All TV :");
rvServer.removeAllViews();
listDirector.clear();
rvRelated.removeAllViews();
listRelated.clear();
//----related rv----------
relatedTvAdapter=new LiveTvHomeAdapter(this,listRelated);
rvRelated.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvRelated.setHasFixedSize(true);
rvRelated.setAdapter(relatedTvAdapter);
imgAddFav.setVisibility(GONE);
serverApater=new ServerApater(this,listDirector);
rvServer.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvServer.setHasFixedSize(true);
rvServer.setAdapter(serverApater);
getTvData(type,id);
llBottom.setVisibility(GONE);
final ServerApater.OriginalViewHolder[] viewHolder = {null};
serverApater.setOnItemClickListener(new ServerApater.OnItemClickListener() {
#Override
public void onItemClick(View view, CommonModels obj, int position, ServerApater.OriginalViewHolder holder) {
iniMoviePlayer(obj.getStremURL(),obj.getServerType(),DetailsActivity.this);
serverApater.chanColor(viewHolder[0],position);
holder.name.setTextColor(getResources().getColor(R.color.colorPrimary));
viewHolder[0] =holder;
}
});
}
}
private void initWeb(String s){
if (isPlaying){
player.release();
}
progressBar.setVisibility(GONE);
webView.loadUrl(s);
webView.setVisibility(VISIBLE);
playerLayout.setVisibility(GONE);
}
public void iniMoviePlayer(String url,String type,Context context){
Log.e("vTYpe :: ",type);
if (type.equals("embed") || type.equals("vimeo") || type.equals("gdrive")){
initWeb(url);
}else {
initVideoPlayer(url,context,type);
}
}
public void initVideoPlayer(String url,Context context,String type){
progressBar.setVisibility(VISIBLE);
if (player!=null){
player.release();
}
webView.setVisibility(GONE);
playerLayout.setVisibility(VISIBLE);
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new
AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new
DefaultTrackSelector(videoTrackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
player.setPlayWhenReady(true);
simpleExoPlayerView.setPlayer(player);
simpleExoPlayerView.setControllerVisibilityListener(new PlayerControlView.VisibilityListener() {
#Override
public void onVisibilityChange(int visibility) {
Log.e("Visibil", String.valueOf(visibility));
if (visibility==0){
imgBack.setVisibility(VISIBLE);
imgFull.setVisibility(VISIBLE);
imgfit.setVisibility(VISIBLE);
}else {
imgBack.setVisibility(GONE);
imgFull.setVisibility(GONE);
imgfit.setVisibility(GONE);
}
}
});
Uri uri = Uri.parse(url);
MediaSource mediaSource = null;
if (type.equals("hls")){
mediaSource = hlsMediaSource(uri,context);
}else if (type.equals("youtube")){
Log.e("youtube url :: ",url);
extractYoutubeUrl(url,context);
}
else if (type.equals("rtmp")){
mediaSource=rtmpMediaSource(uri);
}else {
mediaSource=mediaSource(uri);
}
player.prepare(mediaSource, true, false);
player.addListener(new Player.DefaultEventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playWhenReady && playbackState == Player.STATE_READY) {
isPlaying=true;
progressBar.setVisibility(View.GONE);
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
}
else if (playbackState==Player.STATE_READY){
progressBar.setVisibility(View.GONE);
isPlaying=false;
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
}
else if (playbackState==Player.STATE_BUFFERING) {
isPlaying=false;
progressBar.setVisibility(VISIBLE);
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
} else {
// player paused in any state
isPlaying=false;
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
}
}
});
}
private void extractYoutubeUrl(String url,Context context) {
new YouTubeExtractor(context) {
#Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
if (ytFiles != null) {
int itag = 18;
String downloadUrl = ytFiles.get(itag).getUrl();
Log.e("YOUTUBE::", String.valueOf(downloadUrl));
try {
MediaSource mediaSource = mediaSource(Uri.parse(downloadUrl));
player.prepare(mediaSource, true, false);
}catch (Exception e){
}
}
}
}.extract(url, true, true);
}
private MediaSource rtmpMediaSource(Uri uri){
MediaSource videoSource = null;
RtmpDataSourceFactory dataSourceFactory = new RtmpDataSourceFactory();
videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
return videoSource;
}
private MediaSource hlsMediaSource(Uri uri,Context context){
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/JioTV/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"), bandwidthMeter);
MediaSource videoSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
return videoSource;
}
private MediaSource mediaSource(Uri uri){
return new ExtractorMediaSource.Factory(
new DefaultHttpDataSourceFactory("exoplayer")).
createMediaSource(uri);
}
private void addToFav(String url){
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("success")){
new ToastMsg(DetailsActivity.this).toastIconSuccess(response.getString("message"));
isFav=true;
imgAddFav.setBackgroundResource(R.drawable.outline_favorite_24);
}else {
new ToastMsg(DetailsActivity.this).toastIconError(response.getString("message"));
}
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
new ToastMsg(DetailsActivity.this).toastIconError(getString(R.string.error_toast));
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
private void getTvData(String vtype,String vId){
String type = "&&type="+vtype;
String id = "&id="+vId;
String url = new ApiResources().getDetails()+type+id;
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
swipeRefreshLayout.setRefreshing(false);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(GONE);
try {
tvName.setText(response.getString("tv_name"));
tvDes.setText(response.getString("description"));
V_URL=response.getString("stream_url");
CommonModels model=new CommonModels();
model.setTitle("HD");
model.setStremURL(V_URL);
model.setServerType(response.getString("stream_from"));
listDirector.add(model);
JSONArray jsonArray = response.getJSONArray("all_tv_channel");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
CommonModels models =new CommonModels();
models.setImageUrl(jsonObject.getString("poster_url"));
models.setTitle(jsonObject.getString("tv_name"));
models.setVideoType("tv");
models.setId(jsonObject.getString("live_tv_id"));
listRelated.add(models);
}
relatedTvAdapter.notifyDataSetChanged();
JSONArray serverArray = response.getJSONArray("additional_media_source");
for (int i = 0;i<serverArray.length();i++){
JSONObject jsonObject=serverArray.getJSONObject(i);
CommonModels models=new CommonModels();
models.setTitle(jsonObject.getString("label"));
models.setStremURL(jsonObject.getString("url"));
models.setServerType(jsonObject.getString("source"));
listDirector.add(models);
}
serverApater.notifyDataSetChanged();
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
private void getSeriesData(String vtype,String vId){
String type = "&&type="+vtype;
String id = "&id="+vId;
String url = new ApiResources().getDetails()+type+id;
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
swipeRefreshLayout.setRefreshing(false);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(GONE);
try {
tvName.setText(response.getString("title"));
tvRelease.setText("Release On "+response.getString("release"));
tvDes.setText(response.getString("description"));
//----realted post---------------
JSONArray relatedArray = response.getJSONArray("related_tvseries");
for (int i = 0;i<relatedArray.length();i++){
JSONObject jsonObject=relatedArray.getJSONObject(i);
CommonModels models=new CommonModels();
models.setTitle(jsonObject.getString("title"));
models.setImageUrl(jsonObject.getString("thumbnail_url"));
models.setId(jsonObject.getString("videos_id"));
models.setVideoType("tvseries");
listRelated.add(models);
}
relatedAdapter.notifyDataSetChanged();
//----episode------------
JSONArray mainArray = response.getJSONArray("season");
for (int i = 0;i<mainArray.length();i++){
//epList.clear();
JSONObject jsonObject=mainArray.getJSONObject(i);
CommonModels models=new CommonModels();
String season_name=jsonObject.getString("seasons_name");
models.setTitle(jsonObject.getString("seasons_name"));
Log.e("Season Name 1::",jsonObject.getString("seasons_name"));
JSONArray episodeArray=jsonObject.getJSONArray("episodes");
List<EpiModel> epList=new ArrayList<>();
for (int j=0;j<episodeArray.length();j++){
JSONObject object =episodeArray.getJSONObject(j);
EpiModel model=new EpiModel();
model.setSeson(season_name);
model.setEpi(object.getString("episodes_name"));
model.setStreamURL(object.getString("file_url"));
model.setServerType(object.getString("file_type"));
epList.add(model);
}
models.setListEpi(epList);
listDirector.add(models);
episodeAdapter=new EpisodeAdapter(DetailsActivity.this,listDirector);
rvServer.setAdapter(episodeAdapter);
episodeAdapter.notifyDataSetChanged();
}
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
private void getData(String vtype,String vId){
String type = "&&type="+vtype;
String id = "&id="+vId;
String url = new ApiResources().getDetails()+type+id;
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(GONE);
swipeRefreshLayout.setRefreshing(false);
try {
tvName.setText(response.getString("title"));
tvRelease.setText("Released On "+response.getString("release"));
tvDes.setText(response.getString("description"));
//----realted post---------------
JSONArray relatedArray = response.getJSONArray("related_movie");
for (int i = 0;i<relatedArray.length();i++){
JSONObject jsonObject=relatedArray.getJSONObject(i);
CommonModels models=new CommonModels();
models.setTitle(jsonObject.getString("title"));
models.setImageUrl(jsonObject.getString("thumbnail_url"));
models.setId(jsonObject.getString("videos_id"));
models.setVideoType("movie");
listRelated.add(models);
}
relatedAdapter.notifyDataSetChanged();
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
}
Pass the url of your video, use it like this
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("http://Your URL"), "video/*");
startActivity(Intent.createChooser(intent, "Complete action using"));
For pausing your Exoplayer
exoplayer.playWhenReady(false);
This is my full code below. am coding an android app that can select image from gallery or any where and upload it to Mysql server through php but if image is not selected and the upload button is press the application crashes so i want to implement the function that it shows error dialog / warning dialog if image is not selected from gallery have already implemented it in EditText but cannot implement it in Image. below is my code
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
Just copy this code and paste
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
I need to put a 30sec timer in my otp verfication page after 30secs timer should be gone and the keyboard should pop up. what needs to be done??
Below are my java files.
SignUpFragment.java
SignUpActivity activity;
/**
* Declaring Variables for Views
*/
TextView SignupAlreadyMember;
EditText SignUpName, SignUpEmail,referCode;
Button SignUpRegister;
VirtualApplication virtualApplication;
// Progress dialog
private ProgressDialog pDialog;
public SignUpFragment() {
}
#Override
public void onAttach(Activity activit) {
super.onAttach(activit);
this.activity = (SignUpActivity) activit;
virtualApplication = (VirtualApplication) activity.getApplicationContext();
}
int bodyId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bodyId = getArguments().getInt("output");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sign_up, container, false);
activity.setTempTitle("signup");
inItViews(view);
SignUpRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterUser();
// showVerifyMobileScreen(123);
}
});
SignUpEmail.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
RegisterUser();
}
return false;
}
});
SignupAlreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gotoLoginScreen();
}
});
return view;
}
private void gotoLoginScreen() {
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
activity.finish();
}
public boolean validCellPhone(String number) {
return Patterns.PHONE.matcher(number).matches();
}
private void RegisterUser() {
String email = SignUpEmail.getText().toString().trim();
String name = SignUpName.getText().toString().trim();
String code=referCode.getText().toString().trim();
if (email.isEmpty() ||!SystemUtil.isValidMobile(email)) {
SignUpEmail.setError("Enter Mobile number here");
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phone_number", email);
jsonObject.put("body_id", bodyId);
jsonObject.put("referral_code",code);//referral_code
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
jsonObject.put("imei", SystemUtil.getIMEINumber(activity, tm)) ;
} catch (JSONException e) {
e.printStackTrace();
}
SignUpRegister.setEnabled(false);
requestForRegistration(jsonObject);
}
private void requestForRegistration(JSONObject jsonObject) {
showpDialog();
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, AppConstants.REGISTER_URL, jsonObject, this, this);
customJSONObjectRequest.setTag("Register");
customJSONObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
customJSONObjectRequest.setShouldCache(true);
requestQueue.add(customJSONObjectRequest);
//
}
private void showVerifyMobileScreen(int userId) {
VerificationFragment verificationFragment = new VerificationFragment();
Bundle bundle = new Bundle();
bundle.putInt("userId", userId);
bundle.putString("mobile", SignUpEmail.getText().toString().trim());
verificationFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, verificationFragment).commit();
}
private void inItViews(View view) {
TextView SignUPHeader = (TextView) view.findViewById(R.id.SignUPHeader);
TextView Signupmessage= (TextView) view.findViewById(R.id.Signupmessage);
Signupmessage.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUPHeader.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignupAlreadyMember = (TextView) view.findViewById(R.id.SignupAlreadyMember);
SignupAlreadyMember.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpName = (EditText) view.findViewById(R.id.SignUpName);
SignUpName.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpEmail = (EditText) view.findViewById(R.id.SignUpEmail);
SignUpEmail.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpRegister = (Button) view.findViewById(R.id.SignUpRegister);
SignUpRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
referCode = (EditText) view.findViewById(R.id.referCode);
referCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
SignUpRegister.setEnabled(true);
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
SystemUtil.sysOut("register::::: " + jsonObject.toString());
if (JSONUtil.readBoolean(jsonObject, "status")) {
int userId = JSONUtil.readInt(jsonObject, "user_id");
showVerifyMobileScreen(userId);
}else{
SignUpRegister.setEnabled(true);
}
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
}
VerificationFragment.Java
SignUpActivity activity;
TextView verifyTitleOne, verifyTitleTwo, verifyChnageNumber, verificationResend;
EditText SignUpMobile, VerficationCode;
Button VerificationRegister;
int userId;
String mobile;
boolean isResend;
public VerificationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
userId = bundle.getInt("userId");
mobile = bundle.getString("mobile");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_verfication, container, false);
activity.setTempTitle("details");
inItViews(view);
SignUpMobile.setText("" + mobile);
VerificationRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!VerficationCode.getText().toString().trim().isEmpty()) {
Toast.makeText(activity, "Verifying", Toast.LENGTH_LONG).show();
showpDialog();
getDefaultData();
} else {
VerficationCode.setError("Enter Code");
}
}
});
verificationResend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isResend) {
isResend = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject, AppConstants.RESEND_OTP_URL);
}else
Toast.makeText(activity,"Please Wait",Toast.LENGTH_SHORT).show();
}
});
// setvalues();
return view;
}
private void setvalues() {
VerficationCode.setText("51692");
VerificationRegister.performClick();
}
private void getDefaultData() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", userId);
jsonObject.put("token", VerficationCode.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject,AppConstants.VERIFY_NUMBER_URL);
}
private void requestServer(JSONObject jsonObject, String url) {
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject, this, this);
customJSONObjectRequest.setTag("verify");
requestQueue.add(customJSONObjectRequest);
}
private void gotoSelectSizesPage(JSONObject jsonObject) {
Bundle bundle = new Bundle();
bundle.putString("output", jsonObject.toString());
DoneFragment homeKitFragment = new DoneFragment();
homeKitFragment.setArguments(bundle);
activity.setTempTitle("");
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, homeKitFragment).commit();
}
private void inItViews(View view) {
verifyTitleOne = (TextView) view.findViewById(R.id.verifyTitleOne);
verifyTitleOne.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyTitleTwo = (TextView) view.findViewById(R.id.verifyTitleTwo);
verifyTitleTwo.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyChnageNumber = (TextView) view.findViewById(R.id.verifyChnageNumber);
verifyChnageNumber.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verificationResend = (TextView) view.findViewById(R.id.verificationResend);
verificationResend.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpMobile = (EditText) view.findViewById(R.id.SignUpMobile);
SignUpMobile.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerficationCode = (EditText) view.findViewById(R.id.VerficationCode);
VerficationCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerificationRegister = (Button) view.findViewById(R.id.VerificationRegister);
VerificationRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get("pdus");
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], "3gpp");
smsMessageStr = smsMessage.getMessageBody().toString();
// String address = smsMessage.getOriginatingAddress();
/*smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";*/
}
VerficationCode.setText("" + stripNonDigits(smsMessageStr));
VerificationRegister.performClick();
}
}
};
private ProgressDialog pDialog;
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
public static String stripNonDigits(
final CharSequence input) {
final StringBuilder sb = new StringBuilder(
input.length());
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c > 47 && c < 58) {
sb.append(c);
}
}
return sb.toString();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (SignUpActivity) activity;
activity.registerReceiver(broadcastReceiver, new IntentFilter(
AppConstants.BROADCAST_ACTION_SMS));
}
#Override
public void onDetach() {
super.onDetach();
activity.unregisterReceiver(broadcastReceiver);
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
isResend=false;
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
if (JSONUtil.readBoolean(jsonObject, "status") &&jsonObject.has("user_data")) {
gotoSelectSizesPage(jsonObject);
}
}
}
I need to check the following information on my application, if the text equals "Alpha" then it starts a new activity, else it will go on the usual code. Actually the usual code from "sendPack" work fine without the 'if' rule.
I just run into this problem and don't know how to proceed from here.
its probably a stupid mistake, sorry for this.
how to fix it?
public void Send(View view) throws IOException {
BdLocal bd = new BdLocal(this);
String text = bd.getEmpId();
if (text.equals("Alpha")) {
Intent intent = new Intent(BetaActivity.this, AlphaSetup.class);
startActivityForResult(intent, 0);
} else {
new transmitirInspecao().execute();
}
}
public class sendPack extends AsyncTask<String, Void, String> {
ProgressDialog pdialog;
int boxSelected = 0;
#Override
protected String doInBackground(String... params) {
BdLocal bd = new BdLocal(getApplicationContext());
BdCloud bdc = new BdCloud();
String ret = null;
for (CheckBox aCheckBoxArrayList : checkBoxArrayList) {
if (aCheckBoxArrayList.isChecked()) {
boxSelected++;
try {
int id = (Integer) aCheckBoxArrayList.getTag();
Pack pack = bd.readPackID(id);
ret = bdc.sendPack(pack, params[0], bd.getDspHash());
ret = ret.trim();
if (ret.equals("sucess".trim())) {
bd.MarkAsSend(id);
}
} catch (IOException e) {
//e.printStackTrace();
}
}
}
if (boxSelected <= 0) {
return "none";
}
return ret;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(BetaActivity.this);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setMessage(getResources().getString(R.string.send));
pdialog.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdialog.dismiss();
String msg = "Null";
if (result.equals("success")) {
msg = getResources().getString(R.string.success_send);
} else if (result.equals("img")) {
msg = getResources().getString(R.string.error_ftp);
} else if (result.equals("oper")) {
msg = getResources().getString(R.string.error_operation);
} else if (result.equals("none")) {
msg = getResources().getString(R.string.non_selected);
} else {
msg = getResources().getString(R.string.error_send);
}
AlertDialog alert;
AlertDialog.Builder builder = new AlertDialog.Builder(BetaActivity.this);
builder.setMessage(msg);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
alert = builder.create();
alert.show();
final Dialog login = new Dialog(this); //here is the message "Dialog cannot be applied" to Send, what should i do?
login.setContentView(R.layout.ins_dialog);
login.setTitle(R.string.insira_dados_op);
Button btnLogin = (Button) login.findViewById(R.id.btnLogin);
Button btnCancel = (Button) login.findViewById(R.id.btnCancel);
final EditText txtUsername = (EditText) login.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) login.findViewById(R.id.txtPassword);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtUsername.getText().toString().trim().length() > 0) {
if (txtPassword.getText().toString().trim().length() > 0) {
BdCloud bdc = new BdCloud();
BdLocal bdl = new BdLocal(BetaActivity.this);
String[] ret = bdc.loginOp(txtUsername.getText().toString().trim(), txtPassword.getText().toString().trim(), bdl.getDspHash());
if (ret[0].equals("true")) {
new Send().execute(ret[1]);
login.dismiss();
} else {
Toast.makeText(betaActivity.this, getResources().getString(R.string.error_inval), Toast.LENGTH_LONG).show();
}
} else {
txtPassword.setError(getResources().getString(R.string.error_field_required));
txtPassword.requestFocus();
}
} else {
txtUsername.setError(getResources().getString(R.string.error_field_required));
txtUsername.requestFocus();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login.dismiss();
}
});
login.show();
}
}
I want to request from this webservice in my project. It contains some information and pictures. How do I get the JSON data from the linked webservice using Volley? How do I parse that data?
MainActivity.java
package.com.example.pr;
import java.*;
public class MainActivity extends Activity {
EditText adGiris, soyadGiris, telGiris, ismeGoreArat, TelefonNumarasi;
Button kaydet, guncelle, kisiAra, Ara;
Veritabani v1;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v1 = new Veritabani(this); // veritabanımızdan bir nesne oluşturuldu
adGiris = (EditText) findViewById(R.id.editText1); // Layout'daki
// item'lerden nesne
// oluşturuldu
soyadGiris = (EditText) findViewById(R.id.editText2);
telGiris = (EditText) findViewById(R.id.editText3);
ismeGoreArat = (EditText) findViewById(R.id.editText4);
kaydet = (Button) findViewById(R.id.button1);
kaydet.setOnClickListener(new View.OnClickListener() // Kaydet butonunun
// click event'i
{
#Override
public void onClick(View v) // tıklandığında kaydet metoduna gidecek
// ve orada kayıt işlemi yapacak
{
kaydet(adGiris.getText().toString(), soyadGiris.getText()
.toString(), telGiris.getText().toString());
}
});
guncelle = (Button) findViewById(R.id.button3);
guncelle.setOnClickListener(new View.OnClickListener() // Kaydet
// butonunun
// click event'i
{
#Override
public void onClick(View v) // tıklandığında kaydet metoduna gidecek
// ve orada kayıt işlemi yapacak
{
guncelle();
}
});
kisiAra = (Button) findViewById(R.id.button2);
kisiAra.setOnClickListener(new View.OnClickListener() // kisiAra
// butonunun
// click event'i
{
#Override
public void onClick(View v) // ad'a göre bilgileri çekecek
{
bilgileriCek(ismeGoreArat.getText().toString()); // girilen isim
// alınıp
// metoda
// gönderiliyor
}
});
guncelle.setVisibility(View.INVISIBLE);
}
public void onClick(View v) {
String numara = TelefonNumarasi.getText().toString();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + numara + ""));
startActivity(intent);
}
public void kaydet(String ad, String soyad, String tel) {
try {
SQLiteDatabase db1 = v1.getWritableDatabase();
ContentValues cv1 = new ContentValues();
cv1.put("ad", ad);
cv1.put("soyad", soyad);
cv1.put("tel", tel);
db1.insertOrThrow("kisiler", null, cv1);
db1.close();
Toast.makeText(getApplicationContext(), "Kayıt işlemi tamamlandı",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Kayıt işleminde hata oluştu", Toast.LENGTH_SHORT).show();
}
}
public void guncelle() {
try {
SQLiteDatabase db1 = v1.getWritableDatabase();
ContentValues cv1 = new ContentValues();
cv1.put("id", Integer.valueOf(duzeltilecekVeri.getId().toString()));
cv1.put("ad", duzeltilecekVeri.getAd());
cv1.put("soyad", duzeltilecekVeri.getSoyad());
cv1.put("tel", duzeltilecekVeri.getTel());
String sql="UPDATE kisiler set ad='"+adGiris.getText()+"',soyad='"+soyadGiris.getText()+"',tel='"+telGiris.getText()+"'"
+ "WHERE id="+duzeltilecekVeri.getId();
db1.execSQL(sql);
db1.close();
Toast.makeText(getApplicationContext(), "Düzeltme işlemi tamamlandı",
Toast.LENGTH_SHORT).show();
guncelle.setVisibility(View.INVISIBLE);
kaydet.setVisibility(View.VISIBLE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Düzeltme işleminde hata oluştu", Toast.LENGTH_SHORT)
.show();
}
}
class Veri{
private String id;
private String ad;
private String soyad;
private String tel;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
this.ad = ad;
}
public String getSoyad() {
return soyad;
}
public void setSoyad(String soyad) {
this.soyad = soyad;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
public List<Veri>list=new ArrayList<Veri>();
public Veri duzeltilecekVeri;
public void bilgileriCek(String kisiAd) {
try {
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.select_dialog_singlechoice);
String[] sutunlar = { "id","ad", "soyad", "tel" }; // veritabanındaki
// sütunlar
// gösterildi
SQLiteDatabase db = v1.getReadableDatabase();
Cursor okunanlar = db.query("kisiler", sutunlar, "ad like ?",
new String[] { "%"+kisiAd+"%" }, null, null, null);
// ad'a göre aratma yapıldı. DB.QUERY() metodunda 3. parametre WHERE
// ifadesidir.
// 4.parametre ise WHERE'de yerine koyacağımız parametredir.
list.clear();
Veri veri = new Veri();
while (okunanlar.moveToNext()) // Şarta uyan veriler okundu.
{
veri=new Veri();
veri.setId(okunanlar.getString(okunanlar.getColumnIndex("id")));
veri.setAd(okunanlar.getString(okunanlar.getColumnIndex("ad")));
veri.setSoyad(okunanlar.getString(okunanlar.getColumnIndex("soyad")));
veri.setTel(okunanlar.getString(okunanlar.getColumnIndex("tel")));
arrayAdapter2.add(veri.getAd() + "\n" + veri.getSoyad() + "\n" + veri.getTel()); // Okunan
// veriler
// adapter'e
// alt alta
// eklendi.
list.add(veri);
}
cekilenleriGoster(arrayAdapter2); // Çekilen veriler adapter'e
// dolduruldu ve ilgili metoda
// gönderildi
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Bilgiler Getirilirken Hata Oluştu", Toast.LENGTH_SHORT)
.show();
}
}
public String strName;
public Integer index;
private void cekilenleriGoster(final ArrayAdapter<String> arrayAdapter2)
{
AlertDialog.Builder builderSingle = new AlertDialog.Builder(MainActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Getirilen Kayıtlar");
builderSingle.setNegativeButton("Çıkış",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter2,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
strName = (String) arrayAdapter2.getItem(which).toString();
index=which;
AlertDialog.Builder builderInner = new AlertDialog.Builder(MainActivity.this);
builderInner.setCancelable(false);
builderInner.setMessage(strName);
builderInner.setTitle("Kayıtlar");
builderInner.setPositiveButton("Değiştir",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which)
{
duzeltilecekVeri=list.get(index);
adGiris.setText(duzeltilecekVeri.getAd());
soyadGiris.setText(duzeltilecekVeri.getSoyad());
telGiris.setText(duzeltilecekVeri.getTel());
guncelle.setVisibility(View.VISIBLE);
kaydet.setVisibility(View.INVISIBLE);
}
});
builderInner.setNegativeButton("Ara",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which)
{
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+list.get(index).getTel()));
startActivity(callIntent);
}
});
builderInner.show();
}
});
builderSingle.show();
}
public void dosyaIndir() throws IOException {
db=v1.getWritableDatabase();
org.apache.commons.httpclient.HttpClient hc = new HttpClient();
HttpMethod gm = new GetMethod("http://www.sinerjias.com.tr/jicra/data/android/13.sql");
hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
hc.executeMethod(gm);
int status = gm.getStatusCode();
if (status != 200) {
throw new IOException("Dosya Bulunamadı !!!");
}
InputStream stream = gm.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
db.execSQL(line);
Log.d("tamam", line);
}
//db.execSQL(builder.toString());
}
}
I assume you have already added volley to your project.
1) Create a RequestQueue using Activity (for example) as Context
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://app.petkim.com.tr/rapi/api/rehber";
2). Assuming the response will be a JSONArray (which it is in the given URL), set up a JSONArrayRequest:
JSONArrayRequest jRequest = new JSONArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("onResponse()", "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error handling
}
});
3) Send the request:
queue.add(jRequest);
queue.start();
You will get your JSON in the onResponse() callback.