Image not showing up in launch screen Android Studio - while-loop

I have a project to do that involves downloading images from the internet with asyncTask with a progressbar at the bottom of the image and an infinite loop so it continues to through the images. When I run my code it says it was successful but the images are not showing up in the Android Emulator. If anyone could help that would great, thank you.
This is the code for mainActivity.java:
public class MainActivity extends AppCompatActivity {
String url = "https://cataas.com/cat";
private static XmlPullParser xpp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
ImageView imageView;
public void Loading (View view) {
CatImages catImages = new CatImages();
imageView = findViewById(R.id.imgView);
try {
Bitmap bitmap = catImages.execute(url).get();
bitmap = catImages.execute(url).get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class CatImages extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
URL url;
HttpURLConnection httpURLConnection;
InputStream in;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection)
url.openConnection();
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
while (true) { }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
}
enter code here

Related

IndexOutOfBoundsException: Inconsistency detected error while scrolling

I have a list which is coming from an API which I'm storing in db. Now I'm fetching list from db and showing it in recyclerview. Then removing all data one-by-one from recyclerview listing. This process is being repeated every 10 seconds using JobScheduler. While I'm scrolling, I'm getting this error. I've tried many solutions given in various SO posts like this but it didn't worked.
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionMessageViewHolder{c2276c4 position=31 id=-1, oldPos=-1, pLpos:-1 no parent} androidx.recyclerview.widget.RecyclerView{5223262 VFED..... .F...... 0,0-720,1120 #7f0900d4 app:id/recycler}, adapter:com.sam.testapp.MessageAdapter#4b57ff3, layout:androidx.recyclerview.widget.LinearLayoutManager#735b4b0, context:com.sam.testapp.MainActivity#e780e56
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {
private List<Message> messageList;
public MessageAdapter(List<Message> messageList) {
this.messageList = messageList;
}
protected static class MessageViewHolder extends RecyclerView.ViewHolder {
private ConstraintLayout root;
private TextView umfiTXT, msgTXT;
MessageViewHolder(View view) {
super(view);
root = view.findViewById(R.id.root);
umfiTXT = view.findViewById(R.id.umfiTXT);
msgTXT = view.findViewById(R.id.msgTXT);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MessageViewHolder((LayoutInflater.from(parent.getContext())).inflate(R.layout.row_msg_list, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MessageViewHolder holder, int position) {
try {
holder.umfiTXT.setText("UMFI: " + messageList.get(position).getMessageUMFI());
holder.msgTXT.setText("Message: " + messageList.get(position).getMessageTxt());
}catch(Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
try {
if(messageList.isEmpty())
return 0;
else
return messageList.size();
}catch(Exception e) {
return 0;
}
}
private void clearData() {
this.messageList.clear();
notifyDataSetChanged();
}
public void setData(List<Message> data) {
clearData();
this.messageList.addAll(data);
notifyDataSetChanged();
}
}
public class MainActivity extends AppCompatActivity {
private ArrayList<Message> messageList;
private RecyclerView recycler;
private AppCompatTextView emptyTxt;
private MessageAdapter messageAdapter;
private SqliteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageList = new ArrayList<>();
recycler = findViewById(R.id.recycler);
emptyTxt = findViewById(R.id.emptyTxt);
database = new SqliteDatabase(MainActivity.this);
recycler.setLayoutManager(new LinearLayoutManager(this));
messageAdapter = new MessageAdapter(messageList);
recycler.setAdapter(messageAdapter);
recycler.setItemAnimator(null);
RxBus.subscribe((Consumer<Object>) o -> {
if (o instanceof RxEvent) {
RxEvent data = (RxEvent) o;
System.out.println("SAM: status: " + data.getStatus());
if (data.getStatus() == 1) {
fetchMessageList();
}
}
});
}
private void fetchMessageList(){
messageList.clear();
AndroidNetworking.get(Util.url)
.setPriority(Priority.IMMEDIATE)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray jsonArray) {
try{
System.out.println("SAM: fetchMessageList jsonArray: "+jsonArray);
ArrayList<Message> templist = new ArrayList<>();
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
templist.add(new Message(jsonObject.getString("umfi"), jsonObject.getString("msg_to"), jsonObject.getString("msg_text")));
}
storeListinDB(templist);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onError(ANError error) {
System.out.println("SAM: fetchMessageList onError: "+error.getErrorBody());
}
});
}
private void storeListinDB(ArrayList<Message> templist){
database.insertArrayData(templist);
showList();
}
private void showList(){
try{
//recycler.getRecycledViewPool().clear();
if(messageList.size()>0){
emptyTxt.setVisibility(View.GONE);
messageAdapter.notifyDataSetChanged();
}else{
emptyTxt.setVisibility(View.VISIBLE);
ArrayList<Message> templist = new ArrayList<>();
templist = database.fetchMessageList();
messageAdapter.setData(templist);
System.out.println("SAM: templist size: "+templist.size());
}
System.out.println("SAM: messageList size: "+messageList.size());
//removeAll();
}catch(Exception e){
e.printStackTrace();
}
}
}
You pass your messageList to the adapter, so the messageList in the adapter and in the activity are the same object references. Then, as I understand, somehow method fetchMessageList is called, it's where the problem appears. You call .clear() on your list and start an asynchronous operation to fetch a new list, to then synchronously post it to your adapter.
The thing is, after you have cleared your list, your adapter keeps the reference to an empty list now, without being notified about the changes. The adapter still "thinks" that your list is the same size as it was before, so when you scroll the RecyclerView, it tries to call at least onBindViewHolder for new appearing items. But, as the list is empty, it throws IndexOutOfBoundsException.
You could try to notify the adapter about the changes immediately after calling messageList.clear(), but it seems to me that just deleting this clearing will solve the problem.
private void fetchMessageList(){
//messageList.clear(); <- delete this
AndroidNetworking.get(Util.url)
...
}

Estimote : Show notification when the app is closed

How to show notification when the app is closed with estimote api.As it is having default BeaconService we need to implement it in the application level to show the notification when the app is closed.So for that i'm trying with the following code.
Activity:-
public class Dashboard extends Activity {
private static final String TAG = Dashboard.class.getSimpleName();
ConnectionDetector cDetector;
private static final int NOTIFICATION_ID = 123;
private NotificationManager notificationManager;
JSONParser jParser = new JSONParser();
AlertDialogManager alert;
private static final String URL_NOTIFICATIONS = "";
ArrayList<NameValuePair> pairs;
private static final int REQUEST_ENABLE_BT = 1234;
private ProgressDialog pDialog;
private BeaconManager bManager;
// private Beacon beacon;
private Region region = new Region("regionID", null, null, null);
List<Beacon> beaconList;
BroadcastReceiver receiver;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_demo);
getActionBar().setDisplayHomeAsUpEnabled(true);
cDetector = new ConnectionDetector(getApplicationContext());
// check Internet connection
if (!cDetector.isConnectingToInternet()) {
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working internet connection", false);
return;
}
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region region,
final List<Beacon> beacons) {
// Note that results are not delivered on UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// Note that beacons reported here are already sorted by
// estimated distance between device and beacon.
getActionBar().setSubtitle(
"Found beacons: " + beacons.size());
}
});
}
});
Log.i("BeaconsList", "beaconslist" + beaconList);
// region = new Region("regionId", ((Beacon)
// beaconList).getProximityUUID(),
// ((Beacon) beaconList).getMajor(),
// ((Beacon) beaconList).getMinor());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
// new GetNotificationData().execute();
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
#Override
protected void onStart() {
super.onStart();
// Check if device supports Bluetooth Low Energy.
if (!bManager.hasBluetooth()) {
Toast.makeText(this, "Device does not have Bluetooth Low Energy",
Toast.LENGTH_LONG).show();
return;
}
// If Bluetooth is not enabled, let user enable it.
if (!bManager.isBluetoothEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
connectToService();
}
}
#Override
protected void onStop() {
try {
bManager.stopRanging(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while stopping ranging", e);
}
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
connectToService();
} else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
.show();
getActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService() {
getActionBar().setSubtitle("Scanning...");
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startRanging(region);
} catch (RemoteException e) {
Toast.makeText(
Dashboard.this,
"Cannot start ranging, something terrible happened",
Toast.LENGTH_LONG).show();
Log.e(TAG, "Cannot start ranging", e);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
notificationManager.cancel(NOTIFICATION_ID);
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while starting monitoring");
}
}
});
}
#Override
protected void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
bManager.disconnect();
super.onDestroy();
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(Dashboard.this, Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
Dashboard.this, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(Dashboard.this)
.setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
TextView statusTextView = (TextView) findViewById(R.id.status);
statusTextView.setText(msg);
}
}
Application Class:-
public class MyApplication extends Application {
BeaconManager bManager;
NotificationManager notificationManager;
private Region region = new Region("regionID", null, null, null);
private static final int NOTIFICATION_ID = 123;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region regions, List<Beacon> beacons) {
// TODO Auto-generated method stub
Log.i("Beacons", "" + beacons.size());
}
});
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d("BEACON", "Error while starting monitoring");
}
}
});
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(getApplicationContext(),
Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
getApplicationContext(), 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(
getApplicationContext()).setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
and i have mentioned the beaconservice in manifest also as follows..
Can any one help what is going wrong here and how can show the notification when the app is closed.

Animation not repeating

I am trying to get the text view to zoomin/out 4 times one by one. It works only once and then just dies.
public class MainActivity extends Activity implements AnimationListener {
Animation zoomin, zoomout;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
runOnUiThread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 4; i++) {
zoomin = AnimationUtils.loadAnimation(MainActivity.this,
R.anim.zoomin);
zoomin.setAnimationListener(MainActivity.this);
zoomout = AnimationUtils.loadAnimation(MainActivity.this,
R.anim.zoomout);
text.setAnimation(zoomin);
text.setAnimation(zoomout);
text.startAnimation(zoomin);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
#Override
public void onAnimationEnd(Animation animation) {
text.startAnimation(zoomout);
}
}
change
text.startAnimation(zoonout);
to
text.startAnimation(zoomin);
Hope it helps u. Have a nice day.

How to re-use a mediaplayer after release() and null?

My app has a button which is playing a short mp3 file when clicked. I want to release and reuse the mediaplayer object properly (so it will not interfere other apps) when e.g. user gets a phone call, or home button is being clicked.
If I implement onPause and onStop this way:
#Override
public void onPause() {
super.onPause();
mp.release();
mp = null;
}
#Override
public void onStop() {
super.onStop();
mp.release();
mp = null;
}
then how do I re-use mp when onRestart is being called? is it the right way to do that? maybe I should use mp.stop()?
thanks
Edit: I found a solution myself. re-creating the object again:
#Override
publib void onResume() {
super.onResume();
mp = new MediaPlayer();
}
does the job. still a noob...:) thanks
Use onCompletion
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
myStereo.setLooping(true);
myStereo.release();
try {
myStereo.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myStereo.start();
}

SurfaceView Tutorial problems

I found a tutorial and it looks like this:
package com.djrobotfreak.SVTest;
public class Tutorial2D extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new Panel(this));
}
class Panel extends SurfaceView implements SurfaceHolder.Callback {
private TutorialThread _thread;
public Panel(Context context) {
super(context);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
}
#Override
public void onDraw(Canvas canvas) {
Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(_scratch, 10, 10, null);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
_thread.setRunning(true);
_thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// simply copied from sample application LunarLander:
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
class TutorialThread extends Thread {
private SurfaceHolder _surfaceHolder;
private Panel _panel;
private boolean _run = false;
public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
}
and it does not work, no matter what I do. I am trying to convert my code to surfaceview but I cant find any surfaceview programs that even work (besides the android-provided ones). Does anyone know what the error even is saying?
Here is my logcat info: http://shrib.com/oJB5Bxqs
If you get a ClassNotFoundException, you should check the Manifest file.
Click on the Application tab and look on the botton right side under "Attributes for".
If there is a red X mark under your Class Name, then click on the "Name" link and locate the correct class to load.