Load screen while under async http request - java

On startup, an async class is executed which scrapes a website for information. The screen is left blank during this time, before the gathered information is populated to a listview. Is there any way to add a loading screen during this time?
I looked at this (Add the loading screen in starting of the android application) but I don't think it's what I need because I don't know how long the request will take.
Thanks for your time.
After seeing some of the answers, I revised my code, but neither became visible. here is my xml file for activity main. there is also a textview layout xml file for the default textview element in a listview.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_centerInParent="true"/>
<ListView
android:layout_width="match_parent"
android:layout_height="507dp"
android:id="#+id/listView"
android:smoothScrollbar="true" />
</RelativeLayout>
And here is the main activity's code:
package adam.example.com.stockexample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity {
private int index=-1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView ListStock= (ListView)findViewById(R.id.listView);
final ArrayList<String>symbols= new ArrayList<String>();
final ProgressBar pb= (ProgressBar)findViewById(R.id.progressBar);
List<StockElement> stats= new ArrayList<StockElement>();
List<String> StringList= new ArrayList<String>();
pb.setVisibility(View.VISIBLE);
try {
InputStream inputStream = openFileInput("stocks.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
String []ret = stringBuilder.toString().split(",");
for(int x=0;x<ret.length;x++){
symbols.add(ret[x]);
}
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
for(int x=0;x<symbols.size();x++){
stats.add(addStock(symbols.get(x)));
}
for(int x=0;x<stats.size();x++){
StringList.add(stats.get(x).toString());
}
final ArrayAdapter<String> stockAdapter=
new ArrayAdapter<String>(
getApplicationContext(),
R.layout.list_item_textview,
R.id.list_item_textview,
StringList);
pb.setVisibility(View.GONE);
ListStock.setAdapter(stockAdapter);
final AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setMessage("Are you sure you would like to delete this?")
.setTitle("Warning")
.setPositiveButton("No", null)
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
stockAdapter.remove(stockAdapter.getItem(index));
symbols.remove(index);
WriteBack(symbols);
stockAdapter.notifyDataSetChanged();
}
});
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
TextView ItemText = (TextView) container;
String selectedItemText=(String)ItemText.getText();
String symbol =selectedItemText.substring(selectedItemText.indexOf(":")+1,selectedItemText.lastIndexOf(")"));
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/finance?q="+symbol));
startActivity(browserIntent);
}
};
AdapterView.OnItemLongClickListener itemLongClickListener= new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?>parent, View container, final int position, long id){
TextView ItemText= (TextView) container;
String selectedItemText= (String) ItemText.getText();
index=position;
builder.show();
return true;
}
};
ListStock.setOnItemClickListener(itemClickListener);
ListStock.setOnItemLongClickListener(itemLongClickListener);
}
public void WriteBack(ArrayList <String> list){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("stocks.txt", Context.MODE_PRIVATE));
for(int x=0;x<list.size()-1;x++){
outputStreamWriter.append(list.get(x)+",");
}
outputStreamWriter.append(list.get(list.size()-1));
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public StockElement addStock(String sym){
try {
String s = new HTTPRequest().execute("http://www.google.com/finance?q="+sym).get();
String symbol= s.substring(s.indexOf("<title>")+7,s.indexOf("</title>"));
String name= symbol.substring(0,symbol.indexOf(":"));
symbol=symbol.substring(symbol.indexOf(":")+2,symbol.indexOf(" quotes"));
String price= s.substring(s.indexOf("<meta itemprop=\"price\"")+25,s.indexOf("<meta itemprop=\"price\"")+50);
price= price.substring(price.indexOf("\"")+1,price.lastIndexOf("\""));
String priceChange= s.substring(s.indexOf("<meta itemprop=\"priceChange\"")+36,s.indexOf("<meta itemprop=\"priceChange\"")+60);
priceChange=priceChange.substring(priceChange.indexOf("\"")+1,priceChange.lastIndexOf("\""));
String percent= s.substring(s.indexOf("<meta itemprop=\"priceChangePercent\"")+36,s.indexOf("<meta itemprop=\"priceChangePercent\"")+60);
percent=percent.substring(percent.indexOf("\"")+1,percent.lastIndexOf("\""));
return new StockElement(name,symbol,price,priceChange,percent);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}catch (NullPointerException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

You can add a ProgresBar(circle) in your activity's layout.And in order to set the loading circle right on the middle of the screen you can have your layout something like this.
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:layout_alignParentTop="true"/>
<ProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/> //to make it appear in the middle of screen
Now in your Activity
ProgressBar pb;
pb = (ProgressBar) findViewById(R.id.progress);
Now when the task is in progress i.e when contacting your website, you can set pb.setVisibility(View.VISIBLE);
And as soon as your task is complete just set
pb.setVisibility(View.GONE);
Hope it helps.

Add a view to your XML that has some "Loading" message. Then use the ListView.setEmptyView(View view) method to have the ListView control that view. It will be shown until the ListView is populated with items.

Related

Reading values from Arduino IDE in Android Studio(java) ? There is no mistake as I can see but ıt doesn't work

Have a healthy day. As I mentioned in title, I want to read values from Arduino IDE (ESP32) . I ınstall nRF Connect mobile app because ı want to check if ı'm getting value correctly or not . I got true value.Then I write an android studio code as a beginner and from tutorials ofc. It's pairing devices and then if its name ESP32, ı wanna communicate it with arduiono but ı m getting empty array.After watching tutorials and reading stackoverflow posts ı ve decided to ask for help here. I will be glad if you help me. Thanks.
import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import pl.bclogic.pulsator4droid.library.PulsatorLayout;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> arrayAdapter;
ArrayList<String> stringArrayList = new ArrayList<String>();
private boolean alreadyExecuted = false;
private boolean alreadyExecuted2=false;
BluetoothSocket mmSocket;
BluetoothServerSocket mmServerSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
TextView myLabel;
#SuppressLint("MissingPermission")
private void connectAndTransferDataBT(BluetoothDevice mmDevice) throws IOException{
BluetoothSocket tmp = null;
InputStream tmpIn = null;
OutputStream tmpOut = null;
Handler handler = new Handler();
UUID uuid = UUID.fromString("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
try {
mmSocket.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInputStream = tmpIn;
mmOutputStream = tmpOut;
byte [] mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
assert mmInputStream != null;
numBytes = mmInputStream.read(mmBuffer);
};
private void getLocationPermission()
{
ActivityResultLauncher<String[]> locationPermissionRequest =
registerForActivityResult(new ActivityResultContracts
.RequestMultiplePermissions(), result -> {
Boolean fineLocationGranted = result.getOrDefault(
Manifest.permission.ACCESS_FINE_LOCATION, false);
Boolean coarseLocationGranted = result.getOrDefault(
Manifest.permission.ACCESS_COARSE_LOCATION,false);
if (fineLocationGranted != null && fineLocationGranted) {
} else if (coarseLocationGranted != null && coarseLocationGranted)
{
} else
{
}
}
);
locationPermissionRequest.launch(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
});
}
public void statusCheck() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
}
private void buildAlertMessageNoGps() {
if(!alreadyExecuted) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
Toast.makeText(MainActivity.this, "You have to enable your GPS for using Bluetooth!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
alreadyExecuted = true;
}
}
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
Button scanningBtn = findViewById(R.id.scanningBtn);
ListView listView = findViewById(R.id.listView);
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
PulsatorLayout pulsator = findViewById(R.id.pulsator);
TextView myLabel = findViewById(R.id.myLabel);
if(myBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth Is Not Available on this Device!", Toast.LENGTH_SHORT).show();
}
else
{
if(!myBluetoothAdapter.isEnabled())
{
//later
}
else
{
if(myBluetoothAdapter.isEnabled() && !myBluetoothAdapter.isDiscovering())
{
Intent intent = new Intent ( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent,1);
statusCheck();
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex) {}
if(!gps_enabled) {
buildAlertMessageNoGps();
}
getLocationPermission();
BroadcastReceiver myReceiver = new BroadcastReceiver() {
#SuppressLint("MissingPermission")
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(!stringArrayList.contains("Device : "+device.getName())) {
stringArrayList.add("Device : " + device.getName());
if(!alreadyExecuted2)
{if (device.getName().equals("ESP32")) {
mmDevice = device;
alreadyExecuted2=true;
}}
arrayAdapter.notifyDataSetChanged();
}
}
}
};
scanningBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//scanningBtn.setEnabled(false);
pulsator.start();
myBluetoothAdapter.startDiscovery();
if(mmDevice!=null)
{
try {
connectAndTransferDataBT(mmDevice);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(myReceiver,intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,stringArrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = listView.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//startActivity(new Intent(MainActivity.this,MainScreenActivity.class));
}
});
}
}
}
}
}
xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginTop="25dp"
/>
<Button
android:id="#+id/scanningBtn"
android:layout_width="140dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="25dp"
android:layout_marginBottom="17dp"
android:text="SCAN" />
<TextView
android:id="#+id/myLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<pl.bclogic.pulsator4droid.library.PulsatorLayout
android:id="#+id/pulsator"
android:layout_width="match_parent"
android:layout_height="150dp"
app:pulse_count="4"
app:pulse_duration="3000"
app:pulse_interpolator="Accelerate"
android:layout_marginBottom="17dp"
app:pulse_repeat="0"
app:pulse_startFromScratch="false" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="530dp"
android:background="#color/white"
android:cacheColorHint="#FBF8F8" />
</LinearLayout>
</ScrollView>
</LinearLayout><![CDATA[
/>
]]>
</androidx.appcompat.widget.LinearLayoutCompat>
and arduino code from examples BLE_notify
/*
Video: https://www.youtube.com/watch?v=oCMOYS71NIU
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-
snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
Ported to Arduino ESP32 by Evandro Copercini
updated by chegewara
Create a BLE server that, once we receive a connection, will send periodic
notifications.
The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8
The design of creating the BLE server is:
1. Create a BLE Server
2. Create a BLE Service
3. Create a BLE Characteristic on the Service
4. Create a BLE Descriptor on the characteristic
5. Start the service.
6. Start advertising.
A connect hander associated with the server starts a background task that performs
notification
every couple of seconds.
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 0;
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
Serial.begin(115200);
// Create the BLE Device
BLEDevice::init("ESP32");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
// https://www.bluetooth.com/specifications/gatt/viewer?
attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
// Create a BLE Descriptor
pCharacteristic->addDescriptor(new BLE2902());
// Start the service
pService->start();
// Start advertising
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");
}
void loop() {
if (deviceConnected) {
float temp = 25.5;
char send[8];
dtostrf(temp,2,1,send);
pCharacteristic->setValue((uint8_t*)&send, 4);
pCharacteristic->notify();
value++;
delay(1000); // bluetooth stack will go into congestion, if too many packets are
sent, in 6 hours test i was able to go as low as 3ms
}
// disconnecting
if (!deviceConnected && oldDeviceConnected) {
delay(500); // give the bluetooth stack the chance to get things ready
pServer->startAdvertising(); // restart advertising
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
}
Your ESP32 code is Bluetooth Low Energy while your Android code is Bluetooth Classic.
You have to implement BLE in your android code
https://developer.android.com/guide/topics/connectivity/bluetooth/ble-overview

How to put a progress bar with thread safety in android while hitting a server and waiting for response?

I have an application where I am recording audio in an activity. User has a start recording and stop recording button to do that. Once user clicks the stop recording button, it sends the recorded mp3 file to server (encoded string) and server process it and a response is received. I want to do the following tasks:
Since this process is long, I want to do this in a separate thread(preferably).
The process of sending and receiving response is to be shown using progress bar.
User should be able to navigate to other screens while he is waiting(i.e. current activity may be destroyed)
I tried using Toast messages before and after the function where I send mp3 to server. But there is no sync, sometimes msg comes early, sometime it's late. That's why a proper progress bar is required.How to do this? Can AsyncTask be used with what I want to achieve in (3). or should I use some other form of multithreading. Please help.Below is the activity
(Please ignore the indentations, I couldn't fix the code on stack-overflow:
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class RecordActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private static String msg = "default";
public final static String Result_MESSAGE = "in.innovatehub.ankita_mehta.tinyears.ResultMESSAGE";
private static final int REQUESTCODE_RECORDING = 109201;
private Button mRecorderApp = null;
private static String mFileName = "music.mp3";
private static String mFilePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/TinyEars/"));
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ImageButton mRecordImageButton = null;
private ImageButton mPlayImageButton = null;
boolean mStartRecording = true;
boolean mStartPlaying = true;
private Button mShowStatsButton = null;
private static final String TAG = "RecordActivity";
private Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
handler.postDelayed(this, 1);
if(mRecorder!=null) {
int maxAmplitude = mRecorder.getMaxAmplitude();
if (maxAmplitude != 0) {
// visualizerView.addAmplitude(maxAmplitude);
}
}
else{
}
}
};
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFilePath+"/"+mFileName);
mPlayer.prepare();
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Log.i("Completion Listener", "Song Complete");
stopPlaying();
mRecordImageButton.setEnabled(true);
}
});
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
if (mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
mPlayImageButton.setImageResource(R.drawable.playicon);
// mStartPlaying = true;
} else {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
// mStartPlaying = false;
}
}
private void startRecording() {
AudioRecordTest(String.valueOf(System.currentTimeMillis()));
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFilePath+"/"+mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
try {
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(LOG_TAG, "start() failed");
}
}
private void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
mRecorder = null;
mRecordImageButton.setImageResource(R.drawable.micicon);
// mStartRecording = true;
} else {
mRecordImageButton.setImageResource(R.drawable.stopicon);
// mStartRecording = false;
}
}
public void AudioRecordTest(String text) {
boolean exists = (new File(mFilePath+"/"+mFileName)).exists();
if (!exists) {
new File(mFileName).mkdirs();
}
// mFileName += "audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Log.d(TAG,"HERE IS FILE PATH"+mFilePath+"/"+mFileName);
mRecordImageButton = (ImageButton) findViewById(R.id.imageButton2);
mPlayImageButton = (ImageButton) findViewById(R.id.imageButton3);
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mRecorderApp = (Button) findViewById(R.id.recorderApp);
AudioRecordTest("00000");
mRecordImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onRecord(mStartRecording);
if (mStartRecording) {
mRecordImageButton.setImageResource(R.drawable.stopicon);
mPlayImageButton.setEnabled(false);
//setText("Stop recording");
} else {
mRecordImageButton.setImageResource(R.drawable.micicon);
mPlayImageButton.setEnabled(true);
mShowStatsButton.setEnabled(true);
mShowStatsButton.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Hold on... we are getting the results!",Toast.LENGTH_SHORT).show();
pressedSavBtn();
Toast.makeText(getApplicationContext(),"Parsing done ... now you may see the results!",Toast.LENGTH_SHORT).show();
//setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
mPlayImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onPlay(mStartPlaying);
if (mStartPlaying) {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
mRecordImageButton.setEnabled(false);
mShowStatsButton.setEnabled(false);
//setText("Stop playing");
} else {
mPlayImageButton.setImageResource(R.drawable.playicon);
mRecordImageButton.setEnabled(true);
mShowStatsButton.setEnabled(false);
//setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
//Calling recorder ...
mRecorderApp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (isAvailable(getApplicationContext(), intent)) {
startActivityForResult(intent, REQUESTCODE_RECORDING);
}
}
});
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mShowStatsButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
sendResults(msg);
}
});
}
public void pressedSavBtn(){
try {
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
mShowStatsButton.setVisibility(View.VISIBLE);
}
}
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path = new File(mFilePath+"/");
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//THIS IS FILE ENCODING CODE
File file = new File(mFilePath+"/"+mFileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Log.d("~~~~~~~~ Encoded: ", encoded);
writeToFile(encoded);
//THIS IS URL CONN CODE
String link = "http://192.168.50.0:9000/divide_result";
URL url = new URL(link);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Name", "StackOverFlow"));
nameValuePairs.add(new BasicNameValuePair("Date", encoded));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String sb = convertStreamToString(response.getEntity().getContent());
Log.d(TAG,"MESSAGE NOW"+sb);
Log.d(TAG, sb);
msg = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void sendResults(String res){
Log.d(TAG, "Inside on create, Navigating to Result Screen Activity!");
Intent intent = new Intent(getApplicationContext(), ResultsScreenActivity.class);
intent.putExtra(Result_MESSAGE, res);
startActivity(intent);
}
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUESTCODE_RECORDING) {
if (resultCode == RESULT_OK) {
Uri audioUri = intent.getData();
// make use of this MediaStore uri
// e.g. store it somewhere
}
else {
// react meaningful to problems
}
}
else {
super.onActivityResult(requestCode,
resultCode, intent);
}
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
thread.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updater);
if(mRecorder!=null) {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
handler.post(updater);
}
}
Also below is the layout-xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:screenOrientation="portrait"
android:orientation="vertical"
tools:context="in.innovatehub.mobile.ankita_mehta.tinyears.RecordActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout_record"
android:orientation="vertical"
android:gravity="center">
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/micicon" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/playicon" />
<Button
android:id="#+id/showMeStats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:visibility="gone"
android:onClick="loadStats"
android:text="#string/showMeStats" />
<Button
android:id="#+id/recorderApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:gravity="center"
android:text="#string/UseRecorderApp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loadStatsLinearLayout"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<TextView
android:id="#+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/loadingMessage"
/>
<ProgressBar
android:id="#+id/downloadProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
</LinearLayout>
</LinearLayout>
You can use an IntentService to upload your content to the server. By default, it runs on a seperate thread and is not activity bound. Then use a broadcast receiver to communicate the result back to any activity. You can find an example here.
For the progress bar, you can create a notification and show the progress bar there, this will not block your application's UI.
For hitting the server at you should use AsyncTask or Runnable thread, without disturb the main tread
for custome progress dialog use the following code
xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#color/color_white"
android:padding="5dp" >
<ProgressBar
android:id="#+id/layCustomContentProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/layCustomProgressHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/layCustomProgressInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
and the method
public Dialog getCustomPogressDialog(Context context, String heading, String text) {
// Declare the customer dialog
Dialog dlgProgress = new Dialog(context);
// Set no title for the dialog
dlgProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the content view to the customer_alert layout
dlgProgress.setContentView(R.layout.layout_custom_process_progress);
// Cancel the dialog when touched outside.
dlgProgress.setCanceledOnTouchOutside(false);
// Set the main heading
TextView dlgHeading = (TextView) dlgProgress.findViewById(R.id.layCustomProgressHeading);
dlgHeading.setText(heading);
// set the info
TextView dlgInfo = (TextView) dlgProgress.findViewById(R.id.layCustomProgressInfo);
dlgInfo.setText(text);
// Return the refenrece to the dialog
return dlgProgress;
}

User inputs a url for an image and it displays in a imageview

I'm trying to create an app in Android Studio that allows the user to use an EditText and input a url for an image and then the image gets displayed in a imageview
package com.example.michelle.imageurl;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Image extends Activity {
Button retrieveImage;
ImageView image;
String fileUrl, src;
Bitmap bitmap;
ProgressDialog pDialog;
/*Drawable loadImagefromNetwork(String url){
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src.name");
return d;
}
catch(Exception e)
{
System.out.println("Exc=" + e);
return null;
}
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
retrieveImage = (Button)findViewById(R.id.retrieve);
image = (ImageView)findViewById(R.id.imageView);
loadImageFromURL();
getBitmapFromURL(src);
retrieveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoadImage().execute(fileUrl);
}
});
}
public Bitmap getBitmapFromURL(String src)
{
try
{
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap>
{
#Override
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Image.this);
pDialog.setMessage("Loading Image...");
pDialog.show();
}
}
protected void onPostExecute(Bitmap image) {
if(image != null){
ImageView img = new ImageView(this);
img.setImageBitmap(bitmap);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(Image.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean loadImageFromURL(){
try {
URL myFileUrl = new URL (fileUrl);
HttpURLConnection conn =
(HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
image.setImageBitmap(BitmapFactory.decodeStream(is));
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
This is the code for my main Activity and it's where I'm using the ImageView and bitmap and everything to try and get the image but when I run the app all I get is a constant pop up that just says Loading Image the image never actually loads
This is the activity xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Image">
<EditText
android:layout_width= "150dp"
android:layout_height="wrap_content"
android:id="#+id/image"
android:layout_marginTop="90dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retrieve Image"
android:id="#+id/retrieve"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="100dp"
android:layout_height="50dp"
android:id="#+id/imageView"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true" />
</LinearLayout>
Any help would be greatly appreciated
The method protected void onPostExecute(Bitmap image) needs to be in the private class LoadImage. It looks like you have it just outside of the inner class definition.
You could just use Glide library.
retrieveImage = (Button) findViewById(R.id.retrieve);
imageView = (ImageView) findViewById(R.id.imageView);
final EditText editText = (EditText) findViewById(R.id.image);
retrieveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Glide.with(Main22Activity.this).load(editText.getText().toString()).into(imageView);
}
});
Add these dependencies
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support:support-v4:19.1.0'
Glide Library
Use picasso library its very simple to use and perfect for your task
Picasso.with(context).load(EditText.getText().toString).into(imageView);
Add library to your build.gradle
compile 'com.squareup.picasso:picasso:2.5.2'

Populate list outside of async task

I'm trying to populate a listview with json data (from the web) through an aSync task. I have created a list called myCars earlier on in the script and am having trouble populating it from inside the async thread.
package com.*****.complexlistview;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private List<Car> myCars = new ArrayList<Car>();
protected String[] mBlogPostTitles;
public static final int NUMBER_OF_POSTS = 20; //caps indicate constants
public static final String TAG = MainActivity.class.getSimpleName();//prints name of class without package name
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkAvailable()) {
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask(); // new thread
getBlogPostsTask.execute();// don't call do in background directly
populateListView();
}else{
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object[] params) {
int responseCode = -1;//need to have this variable outside scope of try/catch block
try {
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){ //could have used just 200 value
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONObject jsonResponse = new JSONObject(responseData);
String status = jsonResponse.getString("status");
Log.v(TAG, status);
JSONArray jsonPosts = jsonResponse.getJSONArray("posts");
for(int i=0; i < jsonPosts.length(); i++ ){
JSONObject jsonPost = jsonPosts.getJSONObject(i);
String title = jsonPost.getString("title");
Log.v(TAG, "Post " + i + ": " + title);
myCars.add(new Car(title, 1994, R.drawable.kanye8080s, "Lovable"));
/*myCars.add(new Car("Ford", 1940, R.drawable.stadiumarcadium, "Needing work"));
myCars.add(new Car("Toyota", 1994, R.drawable.kanye8080s, "Lovable"));
myCars.add(new Car("Honda", 1999, R.drawable.meteora, "Great condition"));
myCars.add(new Car("Porsche", 2005, R.drawable.olp, "Awesome"));
myCars.add(new Car("Jeep", 2010, R.drawable.yeezus, "Out of this world"));
myCars.add(new Car("Honda", 1999, R.drawable.meteora, "Great condition"));
myCars.add(new Car("Porsche", 2005, R.drawable.olp, "Awesome"));
myCars.add(new Car("Jeep", 2010, R.drawable.yeezus, "Out of this world"));*/
}
}else{
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(TAG, "Exception caught");
}
catch (IOException e){
Log.e(TAG, "Exception caught");
}
catch (Exception e){//must be in this order, this is the last, general catch
Log.e(TAG, "Exception caught");
}
return "Code: " + responseCode;
}
}
private void populateListView() {
ArrayAdapter<Car> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.carsListView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Car>{
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myCars);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// make sure we have a view to work with
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent,false);
}
//find the car to work with
Car currentCar = myCars.get(position);
//fill the view
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_icon);
imageView.setImageResource(currentCar.getIconID());
//Make:
TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake);
makeText.setText(currentCar.getMake());
//Year
TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear);
yearText.setText("" + currentCar.getYear());
//Condition
TextView conditionText = (TextView) itemView.findViewById(R.id.item_txtCondition);
conditionText.setText(currentCar.getCondition());
return itemView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The myCars list is supposed to get populated inside of the doInBackground function. After, inside of the main activity function, it should call the populateListView function which ties it all together. I'm having difficulty though getting the data out.
Any help would be greatly appreciated, thanks,
-- 24x7
Populate data in Listview using AsyncTask you should override onPostExecute method of AsyncTask to call populateListView() method.do it as:
Override onPostExecute in GetBlogPostsTask class :
#Override
protected void onPostExecute(Void result) {
// call populateListView method here
populateListView();
super.onPostExecute(result);
}

Android app activity button timeout selection

I have a basic android app using the zxing scanner and an activity with 3 buttons. The scanner sends a code to the activity, and the user can choose to clock in, clock out, or cancel the operation. This works fine. I want to add an auto timeout to this process, so that if the user does not click a button in a specific time period, the system will determine if they are in or out (cancel button must be pressed). I have the logic for all of this, but I don't know how to add the timeout logic. There is the initial layout, the activity Java code, the SQLite database object and handler, the zxing integration, and an ASync post. I have included the main java class below, which includes the onClick event and primary integration between zxing and the SQLite (those are omitted).
Any thoughts on how I could implement a basic timeout? I would like a function to be called from the main java class if a button is not pressed, and this function will determine (based on the last selection) if they are in or out.
Thanks for any help or suggestions you can provide.
Main Java Class
package com.neonet.neonetjobcardscanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.neonet.neonetjobcardscanner.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressWarnings("unused")
// remove before launch
public class ClockInOut extends Activity implements OnClickListener, OnInitListener {
private Button btnClockIn;
private Button btnClockOut;
private Button btnCancel;
private String employee;
private String operation;
private TextToSpeech tts;
private IntentIntegrator scanIntegrator;
private neonetpost post;
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale("en", "EN"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock_in_out);
btnClockIn = (Button) findViewById(R.id.btnClockIn);
btnClockOut = (Button) findViewById(R.id.btnClockOut);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnClockIn.setOnClickListener(this);
btnClockOut.setOnClickListener(this);
btnCancel.setOnClickListener(this);
tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan(); // optional scan type can be passed here
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.clock_in_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
post = new neonetpost();
String result = null;
String in = null;
String confirmation = null;
String now = df.format(new Date());
try {
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
if (v.getId() == R.id.btnClockIn) {
in = "true";
if (operation != null)
confirmation = getString(R.string.ttsJobIn);
else
confirmation = getString(R.string.ttsClockIn);
Log.d("Insert: ", "Inserting...");
db.addTimeclockEntry(new TimeclockEntry(Integer.valueOf(employee), now, "IN"));
} else if (v.getId() == R.id.btnClockOut) {
in = "false";
if (operation != null)
confirmation = getString(R.string.ttsJobOut);
else
confirmation = getString(R.string.ttsClockOut);
db.addTimeclockEntry(new TimeclockEntry(Integer.valueOf(employee), now, "OUT"));
} else if (v.getId() == R.id.btnCancel) {
}
db.close();
db.exportDB(getApplicationContext());
if (in != null) {
post.execute(employee, operation, in);
while (result == null) {
result = post.result();
}
tts.speak(confirmation + " " + (operation!=null?result:""), TextToSpeech.QUEUE_FLUSH, null);
}
employee = operation = null;
} catch (Exception e) {
if (e != null) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.e("JobCardScanner",
"ClockInOut.java onclick(): " + String.format(e.toString() + "%n" + errors.toString()));
}
}
if (post.hasError())
Log.e("JobCardScanner", "ClockInOut.java onclick(): " + (result == null ? "NULL" : result));
else
Log.i("JobCardScanner", "ClockInOut.java onClick(): " + (result == null ? "NULL" : result));
scanIntegrator.initiateScan(); // optional scan type can be passed here
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
try {
// retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
// we have a result
final String scanContent = scanningResult.getContents();
// String scanFormat = scanningResult.getFormatName();
if (scanContent.indexOf("E") > -1) {
employee = scanContent.substring(2);
if (operation == null) {
btnClockIn.setText(R.string.btnClockIn);
btnClockOut.setText(R.string.btnClockOut);
} else {
btnClockIn.setText(R.string.btnOperationStart);
btnClockOut.setText(R.string.btnOperationEnd);
}
} else if (scanContent.indexOf("OP:") > -1) {
operation = scanContent.substring(3) + getString(R.string.operation_separator);
tts.speak(getString(R.string.ttsJobScan), TextToSpeech.QUEUE_FLUSH, null);
scanIntegrator.initiateScan();
}
Log.i("JobCardScanner",
"ClockInOut.java onActivityResult(): Received " + scanContent);
} else {
Log.i("JobCardScanner", "ClockInOut.java onActivityResult(): No scan data received");
}
} catch (Exception e) {
if (e != null) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.e("JobCardScanner", "ClockInOut.java onActivityResult(): " + String.format(e.toString() + "%n" + errors.toString()));
}
}
}
#Override
public void onInit(int arg0) {
scanIntegrator.initiateScan();
}
}
Main Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.neonet.neonetjobcardscanner.ClockInOut" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txtClockInOut"
android:textAlignment="center" />
<Button
android:id="#+id/btnClockIn"
style="#style/AppBaseTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:minHeight="#dimen/button_min_height"
android:minWidth="#dimen/button_min_width"
android:text="#string/btnClockIn"
android:textAlignment="center"
android:textSize="#dimen/button_text_size"
android:textStyle="bold" />
<Button
android:id="#+id/btnClockOut"
style="#style/AppBaseTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btnClockIn"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:minHeight="#dimen/button_min_height"
android:minWidth="#dimen/button_min_width"
android:text="#string/btnClockOut"
android:textAlignment="center"
android:textSize="#dimen/button_text_size"
android:textStyle="bold" />
<Button
android:id="#+id/btnCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btnClockOut"
android:layout_centerHorizontal="true"
android:minHeight="#dimen/button_min_height"
android:minWidth="#dimen/button_min_width"
android:textAlignment="center"
android:textSize="#dimen/button_text_size"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:text="#string/btnCancel" />
</RelativeLayout>
Main Activity Layout [Graphical]
http://i.stack.imgur.com/MSL5c.png
The Timer() class and subsequent examples did exactly what was needed!
Reference:
http://android-er.blogspot.com/2013/12/example-of-using-timer-and-timertask-on.html
http://developer.android.com/reference/java/util/Timer.html

Categories

Resources