Pass Image (from Json) in gridView to new Activity - android

I have a gridView in my app containing images. Images are loaded from json over the web. I want that when a user click on any image in the gridView a new activity will open container the image clicked by the user. The images are loaded from links defined in json. I tried but didn't get desired result.
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import com.dragedy.dream.adapter.MyArrayAdapter;
import com.dragedy.dream.model.MyDataModel;
import com.dragedy.dream.parser.JSONParser;
import com.dragedy.dream.utils.InternetConnection;
import com.dragedy.dream.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class memechoose extends AppCompatActivity {
private GridView gridView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memechoose);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
/**
* Binding that List to Adapter
*/
adapter = new MyArrayAdapter(this, list);
/**
* Getting List and Setting List Adapter
*/
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(memechoose.this, MemeEditorActivity.class);
i.putExtra("image_path", list.get(position).getImage());
startActivity(i);
}
});
/**
* Just to know onClick and Printing Hello Toast in Center.
*/
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Dialog for User Interaction
*/
dialog = new ProgressDialog(memechoose.this);
dialog.setTitle("Hey Wait Please...");
dialog.setMessage("I am getting your JSON");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "contacts" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_MEME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
MyDataModel model = new MyDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String image = innerObject.getString(Keys.KEY_MEME_PIC);
/**
* Getting Object from Object "phone"
*/
model.setImage(image);
/**
* Adding name and phone concatenation in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} //else {
// Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
// }
}
}
}
and the activity in which i want to display the images is as follows:
public class MemeEditorActivity extends AppCompatActivity {
private Toolbar toolbar;
private MemeEditorActivity selfRef;
private SharedPreferences setting;
private LinearLayout linlaHeaderProgress;
private float memeEditorLayoutWidth;
private float memeEditorLayoutHeight;
private LinearLayout tutorial;
private LinearLayout memeEditorLayout;
private MemeEditorView memeEditorView;
private ImageView forwardButtonImageView;
private Bitmap memeBitmap;
private File cacheImage_forPassing;
private File myDir;
private String dataDir;
private boolean firsttimes;
private boolean tutorialPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme_editor);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
selfRef = this;
// Transparent bar on android 4.4 or above
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT)
{
Window window = getWindow();
// Translucent status bar
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Translucent navigation bar
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
// Initialize progress bar
linlaHeaderProgress = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
linlaHeaderProgress.bringToFront();
// Initialize tutorial
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
SharedPreferences prefre = getSharedPreferences("Meme_Pref", Context.MODE_PRIVATE);
firsttimes = prefre.getBoolean("Meme_Pref", true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
SharedPreferences.Editor firstTimeEditor = prefre.edit();
// See if tutorial is needed to be shown
tutorial = (LinearLayout)findViewById(R.id.meme_editor_tutorial);
tutorial.setEnabled(false);
tutorial.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View view)
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
});
if(firsttimes)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
firstTimeEditor.putBoolean("Meme_Pref", false);
firstTimeEditor.commit();
}
else if(tutorialPreference)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
}
else
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
// Get the data directory for the app
PackageManager m = getPackageManager();
dataDir = getPackageName();
try
{
PackageInfo p = m.getPackageInfo(dataDir, 0);
dataDir = p.applicationInfo.dataDir;
myDir = new File(dataDir+"/cache");
if(!myDir.exists())
myDir.mkdirs();
if(myDir.setWritable(true))
Log.i("meme", "myDir is writable");
else
Log.i("meme", "myDir is not writable");
}catch(PackageManager.NameNotFoundException e)
{
Log.w("yourtag", "Error Package name not found ", e);
}
// Get the intent and get the image path to be the meme image
Intent shareIntent = getIntent();
String imagePath = shareIntent.getStringExtra("image_path");
// Create the SandboxView
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
// final int memeSize = Integer.valueOf(setting.getString("image_size","720"));
final int memeSize = setting.getInt("image_size", 720);
Log.i("meme", "memeSize = "+memeSize);
memeEditorLayout = (LinearLayout)findViewById(R.id.memeEditorLayout);
memeEditorLayout.setGravity(Gravity.CENTER);
try
{
Log.i("imagePath", imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
memeEditorView = new MemeEditorView(this, bitmap);
memeEditorView.setLayoutParams(new ViewGroup.LayoutParams(memeSize, memeSize));
// Scale the sand box and add it into the layout
ViewTreeObserver viewTreeObserver = memeEditorLayout
.getViewTreeObserver();
// For getting the width and height of a dynamic layout during
// onCreate
viewTreeObserver
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
# Override
public void onGlobalLayout()
{
memeEditorLayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
memeEditorLayoutWidth = memeEditorLayout.getHeight();
memeEditorLayoutHeight = memeEditorLayout.getWidth();
float scalingFactor = memeEditorLayoutWidth/(float)memeSize;
Log.i("memeEditorLayoutWidth", Float.toString(memeEditorLayoutWidth));
Log.i("ScaleFactor", Float.toString(scalingFactor));
memeEditorView.setScaleX(scalingFactor);
memeEditorView.setScaleY(scalingFactor);
}
});
memeEditorLayout.addView(memeEditorView);
// Set save button on click method
forwardButtonImageView = (ImageView)findViewById(R.id.forwardButtonImage);
forwardButtonImageView.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View arg0)
{
forwardButtonImageView.setEnabled(false);
Forward forward = new Forward();
forward.execute();
}
});
}catch(OutOfMemoryError e)
{
Toast.makeText(selfRef, "Your device is out of memory.", Toast.LENGTH_LONG).show();
finish();
}catch(Exception e)
{
Log.i("Meme Editor Activity", e.toString());
Toast.makeText(selfRef, "Ops, something went wrong.", Toast.LENGTH_LONG).show();
finish();
}
}
// Delete a files
private void deleteFile(File file)
{
if(file!=null)
{
Log.i("deleteFile", file.toString()+((file.exists())?" is Exist.":"is not exist!!!!"));
// Check if the file exist
if(file.exists())
// Clear the file inside if it is a directory
if(file.isDirectory())
{
String[] children = file.list();
for(int i = 0;i<children.length;i++)
{
File f = new File(file, children[i]);
if(f.delete())
Log.i("deleteFile", f.getAbsolutePath()+" is deleted....");
else
Log.i("deleteFile", f.getAbsolutePath()+" is not deleted!!!!");
}
}
}
}
# Override
protected void onPause()
{
// Hide the progress bar
linlaHeaderProgress.setVisibility(View.GONE);
forwardButtonImageView.setEnabled(true);
super.onPause();
}
# Override
protected void onResume()
{
super.onResume();
memeEditorView.setEnabled(true);
memeEditorView.resume();
}
# Override
protected void onDestroy()
{
// Try to delete cache if possible
// deleteFile(myDir);
// bp_release();
//memeEditorView.destroyDrawingCache();
super.onDestroy();
}
# Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.meme_editor, 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.
switch(item.getItemId())
{
case R.id.reset_sandbox:
memeEditorView.reset();
return true;
case R.id.action_settings:
Intent intent = new Intent(selfRef, MainActivity.class);
startActivity(intent);
return true;
case android.R.id.home:
// When the action bar icon on the top right is clicked, finish this
// activity
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// save image to a specific places
private void saveImage()
{
// Create the file path and file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = timeStamp+".png";
cacheImage_forPassing = new File(myDir, fname);
// Remove duplicates
if(cacheImage_forPassing.exists())
cacheImage_forPassing.delete();
// Try save the bitmap
try
{
FileOutputStream out = new FileOutputStream(cacheImage_forPassing);
memeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.i("memeCacheLocation", cacheImage_forPassing.toString());
}catch(Exception e)
{
e.printStackTrace();
}
}
// Async task for onClick
class Forward extends AsyncTask<Object,Object,Object>
{
// Before forwarding
# Override
protected void onPreExecute()
{
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
linlaHeaderProgress.bringToFront();
memeEditorView.pause();
memeEditorView.invalidate();
}
// Forwarding
# Override
protected String doInBackground(Object ... arg0)
{
Intent forward = new Intent(selfRef, MainActivity.class);
memeEditorView.setDrawingCacheEnabled(true);
memeEditorView.buildDrawingCache();
memeBitmap = Bitmap.createBitmap(memeEditorView.getDrawingCache());
saveImage();
forward.putExtra("cs4295.memcreator.memeImageCache",
cacheImage_forPassing.getPath());
startActivity(forward);
memeEditorView.setDrawingCacheEnabled(false);
return "DONE";
}
// After forwarding
# Override
protected void onPostExecute(Object result)
{
linlaHeaderProgress.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
// Clear the Bitmap from memory
private void bp_release()
{
if(memeBitmap!=null&&!memeBitmap.isRecycled())
{
memeBitmap.recycle();
memeBitmap = null;
}
}
}

#AC-OpenSource E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/http:/static2.businessinsider.com/image/56e3189152bcd0320c8‌​b5cf7-480/sammy-grin‌​er-success-kid-meme.‌​jpg:
open failed: ENOENT (No such file or directory)
You have a slash before http

Related

when using a void in other class, get error on a null object reference

When I'm trying to use other RFID SDK to get Tag Code. And send to the server to fetch the tag information. But I only can get the RFID SDK demon working. So I just try to add HTTP request method into the demon. but I always get an error about I'm calling a null object reference. when I use
IAcitivity.IMakeHttpCall();
Inventory Activity
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.uk.tsl.rfid.ModelBase;
import com.uk.tsl.rfid.TSLBluetoothDeviceActivity;
import com.uk.tsl.rfid.WeakHandler;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import com.uk.tsl.rfid.asciiprotocol.DeviceProperties;
import com.uk.tsl.rfid.asciiprotocol.commands.FactoryDefaultsCommand;
import com.uk.tsl.rfid.asciiprotocol.enumerations.QuerySession;
import com.uk.tsl.rfid.asciiprotocol.enumerations.TriState;
import com.uk.tsl.rfid.asciiprotocol.parameters.AntennaParameters;
import com.uk.tsl.rfid.asciiprotocol.responders.LoggerResponder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InventoryActivity extends TSLBluetoothDeviceActivity {
// Debug control
private static final boolean D = BuildConfig.DEBUG;
private RequestQueue mVolleyQueue;
// OkHttpClient httpClient = new OkHttpClient();
// The list of results from actions
private ArrayAdapter<String> mResultsArrayAdapter;
private ListView mResultsListView;
private ArrayAdapter<String> mBarcodeResultsArrayAdapter;
private ListView mBarcodeResultsListView;
// The text view to display the RF Output Power used in RFID commands
private TextView mPowerLevelTextView;
// The seek bar used to adjust the RF Output Power for RFID commands
private SeekBar mPowerSeekBar;
// The current setting of the power level
private int mPowerLevel = AntennaParameters.MaximumCarrierPower;
// Error report
private TextView mResultTextView;
// Custom adapter for the session values to display the description rather than the toString() value
public class SessionArrayAdapter extends ArrayAdapter<QuerySession> {
private final QuerySession[] mValues;
public SessionArrayAdapter(Context context, int textViewResourceId, QuerySession[] objects) {
super(context, textViewResourceId, objects);
mValues = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getView(position, convertView, parent);
view.setText(mValues[position].getDescription());
return view;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getDropDownView(position, convertView, parent);
view.setText(mValues[position].getDescription());
return view;
}
}
// The session
private QuerySession[] mSessions = new QuerySession[] {
QuerySession.SESSION_0,
QuerySession.SESSION_1,
QuerySession.SESSION_2,
QuerySession.SESSION_3
};
// The list of sessions that can be selected
private SessionArrayAdapter mSessionArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
mVolleyQueue = Volley.newRequestQueue(this);
mResultsArrayAdapter = new ArrayAdapter<String>(this,R.layout.result_item);
mBarcodeResultsArrayAdapter = new ArrayAdapter<String>(this,R.layout.result_item);
mResultTextView = (TextView)findViewById(R.id.resultTextView);
// Find and set up the results ListView
mResultsListView = (ListView) findViewById(R.id.resultListView);
mResultsListView.setAdapter(mResultsArrayAdapter);
mResultsListView.setFastScrollEnabled(true);
mBarcodeResultsListView = (ListView) findViewById(R.id.barcodeListView);
mBarcodeResultsListView.setAdapter(mBarcodeResultsArrayAdapter);
mBarcodeResultsListView.setFastScrollEnabled(true);
// Hook up the button actions
Button sButton = (Button)findViewById(R.id.扫描开始);
sButton.setOnClickListener(mScanButtonListener);
Button cButton = (Button)findViewById(R.id.清除按钮);
cButton.setOnClickListener(mClearButtonListener);
// The SeekBar provides an integer value for the antenna power
mPowerLevelTextView = (TextView)findViewById(R.id.powerTextView);
mPowerSeekBar = (SeekBar)findViewById(R.id.powerSeekBar);
mPowerSeekBar.setOnSeekBarChangeListener(mPowerSeekBarListener);
// Set the seek bar current value to maximum and to cover the range of the power settings
setPowerBarLimits();
mSessionArrayAdapter = new SessionArrayAdapter(this, android.R.layout.simple_spinner_item, mSessions);
// Find and set up the sessions spinner
Spinner spinner = (Spinner) findViewById(R.id.sessionSpinner);
mSessionArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mSessionArrayAdapter);
spinner.setOnItemSelectedListener(mActionSelectedListener);
spinner.setSelection(0);
// Set up Fast Id check box listener
CheckBox cb = (CheckBox)findViewById(R.id.fastIdCheckBox);
cb.setOnClickListener(mFastIdCheckBoxListener);
//
// An AsciiCommander has been created by the base class
//
AsciiCommander commander = getCommander();
// Add the LoggerResponder - this simply echoes all lines received from the reader to the log
// and passes the line onto the next responder
// This is added first so that no other responder can consume received lines before they are logged.
commander.addResponder(new LoggerResponder());
// Add a synchronous responder to handle synchronous commands
commander.addSynchronousResponder();
//Create a (custom) model and configure its commander and handler
mModel = new InventoryModel();
mModel.setCommander(getCommander());
mModel.setHandler(mGenericModelHandler);
}
#Override
public synchronized void onPause() {
super.onPause();
mModel.setEnabled(false);
// Unregister to receive notifications from the AsciiCommander
LocalBroadcastManager.getInstance(this).unregisterReceiver(mCommanderMessageReceiver);
}
#Override
public synchronized void onResume() {
super.onResume();
mModel.setEnabled(true);
// Register to receive notifications from the AsciiCommander
LocalBroadcastManager.getInstance(this).registerReceiver(mCommanderMessageReceiver,
new IntentFilter(AsciiCommander.STATE_CHANGED_NOTIFICATION));
displayReaderState();
UpdateUI();
}
//----------------------------------------------------------------------------------------------
// Menu
//----------------------------------------------------------------------------------------------
private MenuItem mReconnectMenuItem;
private MenuItem mConnectMenuItem;
private MenuItem mDisconnectMenuItem;
private MenuItem mResetMenuItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reader_menu, menu);
mResetMenuItem = menu.findItem(R.id.reset_reader_menu_item);
mReconnectMenuItem = menu.findItem(R.id.reconnect_reader_menu_item);
mConnectMenuItem = menu.findItem(R.id.insecure_connect_reader_menu_item);
mDisconnectMenuItem= menu.findItem(R.id.disconnect_reader_menu_item);
return true;
}
/**
* Prepare the menu options
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean isConnecting = getCommander().getConnectionState() == AsciiCommander.ConnectionState.CONNECTING;
boolean isConnected = getCommander().isConnected();
mResetMenuItem.setEnabled(isConnected);
mDisconnectMenuItem.setEnabled(isConnected);
mReconnectMenuItem.setEnabled(!(isConnecting || isConnected));
mConnectMenuItem.setEnabled(!(isConnecting || isConnected));
return super.onPrepareOptionsMenu(menu);
}
/**
* Respond to menu item selections
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reconnect_reader_menu_item:
Toast.makeText(this.getApplicationContext(), "重新连接中...", Toast.LENGTH_LONG).show();
reconnectDevice();
UpdateUI();
return true;
case R.id.insecure_connect_reader_menu_item:
// Choose a device and connect to it
selectDevice();
return true;
case R.id.disconnect_reader_menu_item:
Toast.makeText(this.getApplicationContext(), "断开连接中...", Toast.LENGTH_SHORT).show();
disconnectDevice();
displayReaderState();
return true;
case R.id.reset_reader_menu_item:
resetReader();
UpdateUI();
return true;
}
return super.onOptionsItemSelected(item);
}
//
private void UpdateUI() {
//boolean isConnected = getCommander().isConnected();
//TODO: configure UI control state
}
private void scrollResultsListViewToBottom() {
mResultsListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
mResultsListView.setSelection(mResultsArrayAdapter.getCount() - 1);
}
});
}
private void scrollBarcodeListViewToBottom() {
mBarcodeResultsListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
mBarcodeResultsListView.setSelection(mBarcodeResultsArrayAdapter.getCount() - 1);
}
});
}
//----------------------------------------------------------------------------------------------
// AsciiCommander message handling
//----------------------------------------------------------------------------------------------
//
// Handle the messages broadcast from the AsciiCommander
//
private BroadcastReceiver mCommanderMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (D) { Log.d(getClass().getName(), "AsciiCommander state changed - isConnected: " + getCommander().isConnected()); }
String connectionStateMsg = intent.getStringExtra(AsciiCommander.REASON_KEY);
Toast.makeText(context, connectionStateMsg, Toast.LENGTH_SHORT).show();
displayReaderState();
if( getCommander().isConnected() )
{
// Update for any change in power limits
setPowerBarLimits();
// This may have changed the current power level setting if the new range is smaller than the old range
// so update the model's inventory command for the new power value
mModel.getCommand().setOutputPower(mPowerLevel);
mModel.resetDevice();
mModel.updateConfiguration();
}
UpdateUI();
}
};
//----------------------------------------------------------------------------------------------
// Reader reset
//----------------------------------------------------------------------------------------------
//
// Handle reset controls
//
private void resetReader() {
try {
// Reset the reader
FactoryDefaultsCommand fdCommand = FactoryDefaultsCommand.synchronousCommand();
getCommander().executeCommand(fdCommand);
String msg = "Reset " + (fdCommand.isSuccessful() ? "succeeded" : "failed");
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
//----------------------------------------------------------------------------------------------
// Power seek bar
//----------------------------------------------------------------------------------------------
//
// Set the seek bar to cover the range of the currently connected device
// The power level is set to the new maximum power
//
private void setPowerBarLimits()
{
DeviceProperties deviceProperties = getCommander().getDeviceProperties();
mPowerSeekBar.setMax(deviceProperties.getMaximumCarrierPower() - deviceProperties.getMinimumCarrierPower());
mPowerLevel = deviceProperties.getMaximumCarrierPower();
mPowerSeekBar.setProgress(mPowerLevel - deviceProperties.getMinimumCarrierPower());
}
//
// Handle events from the power level seek bar. Update the mPowerLevel member variable for use in other actions
//
private OnSeekBarChangeListener mPowerSeekBarListener = new OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Nothing to do here
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Update the reader's setting only after the user has finished changing the value
updatePowerSetting(getCommander().getDeviceProperties().getMinimumCarrierPower() + seekBar.getProgress());
mModel.getCommand().setOutputPower(mPowerLevel);
mModel.updateConfiguration();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePowerSetting(getCommander().getDeviceProperties().getMinimumCarrierPower() + progress);
}
};
private void updatePowerSetting(int level) {
mPowerLevel = level;
mPowerLevelTextView.setText( mPowerLevel + " dBm");
}
//----------------------------------------------------------------------------------------------
// Button event handlers
//----------------------------------------------------------------------------------------------
// Scan action
private OnClickListener mScanButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
mResultTextView.setText("");
// Perform a transponder scan
IMakeHttpCall();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Clear action
private OnClickListener mClearButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
// Clear the list
mResultsArrayAdapter.clear();
mBarcodeResultsArrayAdapter.clear();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//----------------------------------------------------------------------------------------------
// Handler for changes in session
//----------------------------------------------------------------------------------------------
private AdapterView.OnItemSelectedListener mActionSelectedListener = new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if( mModel.getCommand() != null ) {
QuerySession targetSession = (QuerySession)parent.getItemAtPosition(pos);
mModel.getCommand().setQuerySession(targetSession);
mModel.updateConfiguration();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
//----------------------------------------------------------------------------------------------
// Handler for changes in FastId
//----------------------------------------------------------------------------------------------
private OnClickListener mFastIdCheckBoxListener = new OnClickListener() {
public void onClick(View v) {
try {
CheckBox fastIdCheckBox = (CheckBox)v;
mModel.getCommand().setUsefastId(fastIdCheckBox.isChecked() ? TriState.YES : TriState.NO);
mModel.updateConfiguration();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
public void IMakeHttpCall(){
String url = "http://192.168.1.76:4300/lottem/query/toolsstockInventory/";
Uri.Builder builder = Uri.parse(url).buildUpon();
builder.appendQueryParameter("barCode", "1121212121");
JsonArrayRequest jsonObjRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
try {
JSONObject person;
for (int i = 0; i < response.length(); i++) {
person = response.getJSONObject(i);
String name = person.getString(("toolsName"));
mResultTextView.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// For ClientError, 400 & 401, Errors happening on client side when sending api request.
// In this case you can check how client is forming the api and debug accordingly.
// For ServerError 5xx, you can do retry or handle accordingly.
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
});
//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. Volley does retry for you if you have specified the policy.
mVolleyQueue.add(jsonObjRequest);
}
}
InventoryModel
//----------------------------------------------------------------------------------------------
// Copyright (c) 2013 Technology Solutions UK Ltd. All rights reserved.
//----------------------------------------------------------------------------------------------
package com.uk.tsl.rfid.samples.inventory;
import android.util.Log;
import com.uk.tsl.rfid.ModelBase;
import com.uk.tsl.rfid.asciiprotocol.commands.BarcodeCommand;
import com.uk.tsl.rfid.asciiprotocol.commands.FactoryDefaultsCommand;
import com.uk.tsl.rfid.asciiprotocol.commands.InventoryCommand;
import com.uk.tsl.rfid.asciiprotocol.enumerations.TriState;
import com.uk.tsl.rfid.asciiprotocol.responders.IBarcodeReceivedDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.ICommandResponseLifecycleDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.ITransponderReceivedDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.TransponderData;
import com.uk.tsl.utils.HexEncoding;
import java.util.Locale;
public class InventoryModel extends ModelBase
{
// Control
private boolean mAnyTagSeen;
private boolean mEnabled;
public boolean enabled() { return mEnabled; }
private InventoryActivity IAcitivity;
public void setEnabled(boolean state)
{
boolean oldState = mEnabled;
mEnabled = state;
// Update the commander for state changes
if(oldState != state) {
if( mEnabled ) {
// Listen for transponders
getCommander().addResponder(mInventoryResponder);
// Listen for barcodes
getCommander().addResponder(mBarcodeResponder);
} else {
// Stop listening for transponders
getCommander().removeResponder(mInventoryResponder);
// Stop listening for barcodes
getCommander().removeResponder(mBarcodeResponder);
}
}
}
// The command to use as a responder to capture incoming inventory responses
private InventoryCommand mInventoryResponder;
// The command used to issue commands
private InventoryCommand mInventoryCommand;
// The command to use as a responder to capture incoming barcode responses
private BarcodeCommand mBarcodeResponder;
// The inventory command configuration
public InventoryCommand getCommand() { return mInventoryCommand; }
public InventoryModel()
{
// This is the command that will be used to perform configuration changes and inventories
mInventoryCommand = new InventoryCommand();
mInventoryCommand.setResetParameters(TriState.YES);
// Configure the type of inventory
mInventoryCommand.setIncludeTransponderRssi(TriState.YES);
mInventoryCommand.setIncludeChecksum(TriState.YES);
mInventoryCommand.setIncludePC(TriState.YES);
mInventoryCommand.setIncludeDateTime(TriState.YES);
// Use an InventoryCommand as a responder to capture all incoming inventory responses
mInventoryResponder = new InventoryCommand();
// Also capture the responses that were not from App commands
mInventoryResponder.setCaptureNonLibraryResponses(true);
// Notify when each transponder is seen
mInventoryResponder.setTransponderReceivedDelegate(new ITransponderReceivedDelegate() {
int mTagsSeen = 0;
#Override
public void transponderReceived(final TransponderData transponder, boolean moreAvailable) {
mAnyTagSeen = true;
final String tidMessage = transponder.getTidData() == null ? "" : HexEncoding.bytesToString(transponder.getTidData());
final String infoMsg = String.format(Locale.US, "\nRSSI: %d PC: %04X CRC: %04X", transponder.getRssi(), transponder.getPc(), transponder.getCrc());
IAcitivity.IMakeHttpCall();
sendMessageNotification("条形码:"+transponder.getEpc());
mTagsSeen++;
if( !moreAvailable) {
sendMessageNotification("");
Log.d("扫描次数",String.format("扫描到的次数: %s", mTagsSeen));
}
}
});
}

Android Volley doesn't load data from the Server after recreating of the Activity

I have one big problem that is bugging me for a couple of days right now. In the application I am working on, I have couple of activities, and one of them is central (BaseActivity) from which the app goes to other Activities and in each of them it works with Volley Library to fetch data from the API.
So for instance, if I go from BaseActivity to SelectionActivity, in SelectionActivity I receive my recycle view with all the necessary data. That is quite alright, that's what I need.
However, when I finish the activity either by clicking back button or home button on the toolbar, and then want to return back to the SelectionActivity again, the data is not being loaded again. It doesn't state any exception, just doesn't load anything.
I have been searching all over the Internet but I can't seem to find the solution.
EDIT: OK further when I investigated with the debugger. It seems like everything should work because it goes through the response, and through everything. However, instead of RecyclerView filled with data, I don't see anything.
SelectionController Method:
public void getAllJobs()
{
queue = VolleyRequestHandler.getInstance(false).getQueue();
JsonArrayRequest jobsRequest = new JsonArrayRequest(Request.Method.GET,makeAllJobsRequest(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<Job> jobs = new ArrayList<>();
Job job;
try
{
for (int i=0; i<response.length(); i++)
{
JSONObject dbJob = response.getJSONObject(i);
job = new Job();
job.setId(dbJob.getLong("JobId"));
job.setName(dbJob.getString("JobText"));
job.setCustName(dbJob.getString("CustomerName"));
jobs.add(job);
}
// Entries are being sorted!
Collections.sort(jobs, new CustomerComparator());
injection.onGettingAllJobs(jobs);
}
catch (JSONException e)
{
e.printStackTrace();
injection.onErrorSelection(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
injection.onErrorSelection(error.getMessage());
}
});
jobsRequest.setTag(injection.GET_JOBS_TAG);
jobsRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(10),//time out in 10second
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,//DEFAULT_MAX_RETRIES = 1;
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jobsRequest);
}
SelectionInjection interface:
public interface SelectionInjection
{
public static final String GET_JOBS_TAG = "SELECTION_GET_JOBS_TAG";
public static final String GET_TASKS_TAG = "SELECTION_GET_TASKS_TAG";
public static final String SAVE_ENTRY_TAG ="SELECTION_SAVE_ENTRY_TAG";
public void onGettingAllJobs(List<Job> jobs);
public void onGettingTasksForJob(List<Task> tasks);
public void onSavedEntry(TimeEntry savedEntry);
public void onErrorSelection(String message);
}
SelectionActivity:
public class SelectionActivity extends ActionBarActivity implements SelectionInjection {
private static final String TAG = SelectionActivity.class.getName();
/*
* Init variables for Recycler Views
* */
private LinearLayoutManager mLayoutManager;
private SelectJobAdapter mJobsAdapter;
private StickyHeadersItemDecoration headers;
private SelectTaskAdapter mSelectTaskAdapter;
/*
* Lists used for adapter and for storing information from server
* */
private List<Job> mJobs;
private List<Task> mTasks;
private SelectionController controller;
private Job selectedJob;
// Inject Views with ButterKnife
#InjectView(R.id.select_job_recyclerview) SuperRecyclerView mJobSuperRecyclerView;
#InjectView(R.id.select_task_recyclerview) SuperRecyclerView mTaskSuperRecyclerView;
#InjectView(R.id.job_view)FrameLayout mJobView;
#InjectView(R.id.task_view) FrameLayout mTaskView;
#InjectView(R.id.toolbar_actionbar) Toolbar mToolbarAction;
private int mAnimDuration;
// private SelectionTask mFetchingTask; // Is it a good idea to Init it here? -> Nej
// private SaveSelectionTask mSavingTask;
// TODO: Figure out why after coming back again to this activity, there is only a loading wheel and nothing shows up
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
ButterKnife.inject(this);
/*
* Setting up stuff for ViewSwitching
* */
mTaskView.setVisibility(View.GONE); // Also set in XMl but just in case :D
mAnimDuration = getResources()
.getInteger(android.R.integer.config_mediumAnimTime);
/*
* Setting Up Action Bar
* */
mToolbarAction.setTitle(getString(R.string.select_job_title));
setSupportActionBar(mToolbarAction);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true); // Hierarchical activity
if (mJobs == null) {
// provifing dummy test data
Log.v(TAG, "mJobs are are null");
// mJobs = new ArrayList<Job>();
// List<Task> taskList = new ArrayList<Task>();
// taskList.add(
// new Task(88,"Task Name Doh")
// );
// taskList.add(
// new Task(99,"Another Task Name Doh")
// );
// mJobs.add(
// new Job(
// 10,
// "Test Job",
// 1337,
// "Fake Customer",
// taskList
// ));
fetchJobs();
}
else
{
setUpJobRecyclerView();
}
}
private void fetchJobs() {
Log.v(TAG,"fetchJobs();");
// mFetchingTask = new SelectionTask();
// mFetchingTask.execute(); // No PAram, get all the jobs
controller = SelectionController.getInstance(BaseActivity.currentUser,this);
controller.getAllJobs();
}
private void fetchTasks(Job job){
Log.v(TAG,"fetchTAsks()");
try{
// mFetchingTask = new SelectionTask();
// mFetchingTask.execute(job);
controller = SelectionController.getInstance(BaseActivity.currentUser,this);
controller.getTasksForJob(job);
}catch (Exception e){
Log.v(TAG,"There was an error fetching tasks");
e.printStackTrace();
Toast.makeText(this,"There was error fetching tasks",Toast.LENGTH_LONG).show();
}
}
/**
* Method for setting up Job Recycler View
*/
private void setUpJobRecyclerView(){
/*
* Setting up Jobs Recycler View
* */
mJobsAdapter = new SelectJobAdapter(mJobs);
mJobsAdapter.setHasStableIds(true);
headers = new StickyHeadersBuilder()
.setAdapter(mJobsAdapter)
.setRecyclerView(mJobSuperRecyclerView.getRecyclerView())
.setStickyHeadersAdapter(new SelectJobHeaderAdapter(mJobs))
.build();
mJobSuperRecyclerView.setAdapter(mJobsAdapter);
mJobSuperRecyclerView.addItemDecoration(headers);
mLayoutManager = new LinearLayoutManager(this);
mJobSuperRecyclerView.setLayoutManager(mLayoutManager);
// Setting up onClickListener
mJobSuperRecyclerView.
addOnItemTouchListener(
new RecyclerUtils.RecyclerItemClickListener(
this,
new RecyclerUtils.RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
selectedJob = mJobs.get(position);
showMaterialDialog(position);
}
}));
}
/**
* Method used for settigng up and initalising all the adapters
* for TaskRecyclerView
* */
private void setUpTaskRecyclerView() {
mLayoutManager = new LinearLayoutManager(this);
mTaskSuperRecyclerView.setLayoutManager(mLayoutManager);
mSelectTaskAdapter = new SelectTaskAdapter(mTasks);
mSelectTaskAdapter.setHasStableIds(true);
headers = new StickyHeadersBuilder()
.setAdapter(mSelectTaskAdapter)
.setRecyclerView(mTaskSuperRecyclerView.getRecyclerView())
.setStickyHeadersAdapter(new SelectTaskHeaderAdapter(mTasks))
.build();
mTaskSuperRecyclerView.setAdapter(mSelectTaskAdapter);
mTaskSuperRecyclerView.addItemDecoration(headers);
mTaskSuperRecyclerView.
addOnItemTouchListener(
new RecyclerUtils.RecyclerItemClickListener(
this,
new RecyclerUtils.RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.v(TAG,"TaskRecyclerView onItemClick");
Toast.makeText(getApplicationContext(),"The Task has been added",Toast.LENGTH_LONG).show();
// mSavingTask = new SaveSelectionTask();
// mSavingTask.execute(mTasks.get(position));
}
}));
}
/**
* A method that starts a corssfade Animation between JobView and TaskView
*
*/
private void crossfadeViews(final View fromView, View toView){
// Set the Task view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
toView.setAlpha(0f);
toView.setVisibility(View.VISIBLE);
// Animate the Task view to 100% opacity, and clear any animation
// listener set on the view.
toView.animate()
.alpha(1f)
.setDuration(mAnimDuration)
.setListener(null);
// Animate the Job view to 0% opacity. After the animation ends,
// set its visibility to GONE as an optimization step (it won't
// participate in layout passes, etc.)
fromView.animate()
.alpha(0f)
.setDuration(mAnimDuration)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
fromView.setVisibility(View.GONE);
}
});
}
/**
* Method that creates and shows a Dialog
* and executes fetchTasks() if given option is picked.
*/
private void showMaterialDialog(final int position){
// TODO: Consider starting running he Async Task straight away as
// it might be likely that the user will pick "Pcik A Task" option
// and this might speed up the process
Log.v(TAG,"showMAterialDialog");
new MaterialDialog.Builder(this)
.title("Choose Action")
.positiveText("Add Job")
.negativeText("Pick A Task")
.neutralText("CANCEL")
.callback(new MaterialDialog.ButtonCallback(){
#Override
public void onPositive(MaterialDialog dialog) {
// Add Job
Log.v(TAG,"Adding the whole Job");
// mSavingTask = new SaveSelectionTask();
// mSavingTask.execute();
controller = SelectionController.getInstance(BaseActivity.currentUser,SelectionActivity.this);
controller.saveNewTimeEntry(BaseActivity.selectedDate,selectedJob,null);
}
#Override
public void onNegative(MaterialDialog dialog) {
/**
*Pick a Task
*/
fetchTasks(mJobs.get(position));
Log.v(TAG, "Switching Views");
crossfadeViews(mJobView, mTaskView);
}
#Override
public void onNeutral(MaterialDialog dialog) {
Log.v(TAG,"Cancelling the Dialog Choice");
}
}).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.global, 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();
try
{
switch(id)
{
case R.id.action_settings:
return true;
case android.R.id.home:
if (mTaskView.getVisibility() == View.VISIBLE)
{
crossfadeViews(mTaskView,mJobView);
}
else
{
finish();
}
return true;
default:
throw new Exception();
}
}
catch (Exception e)
{
e.printStackTrace();
return super.onOptionsItemSelected(item);
}
}
#Override
public void onSavedEntry(TimeEntry savedEntry)
{
Log.v("SAVED ENTRY", "TRUE");
System.out.println(savedEntry.toString());
controller.closeQueue(SAVE_ENTRY_TAG);
}
#Override
public void onGettingAllJobs(List<Job> jobs) {
mJobs = jobs;
setUpJobRecyclerView();
controller.closeQueue(GET_JOBS_TAG);
}
#Override
public void onGettingTasksForJob(List<Task> tasks) {
mTasks = tasks;
setUpTaskRecyclerView();
controller.closeQueue(GET_TASKS_TAG);
}
#Override
public void onErrorSelection(String message) {
Log.v(TAG,"onErrorJobTask");
}
}
So after a lot of debugging, I have come across to the solution:
It seemed like the way I was making Controllers and Injections didn't really fit into the Android development so I have restructured the code back into the activities and fragments and all works now.
EDIT:
Finally I have figured out what the ACTUAL problem is. When I was passing the Context to the Controller.. I only did so when I actually instantiated them. And because Controllers are singletons in my case, I have been using the old context when reentering Activity.
I can't believe how I did not get that. :)

Android AsyncTask Activity Crash RSS Reader

I'm trying to build an RSS reader and put the rss feed fetch as ansyctask,
that returns a feed in list view, or returns a text view saying "no internet connection"
but the app still crashes, I don't know what's wrong, can you help please.
here is the code:
package rss;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.enporan.polytechoran.R;
public class RSSActivity extends ActionBarActivity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
rssfeedget alpha = new rssfeedget();
alpha.execute();
}
private class rssfeedget extends AsyncTask<String, Void, FeedSource> {
protected void onPreExecute() {
}
#Override
protected FeedSource doInBackground(String... params) {
FeedSource f = new HttpFeedSource();
if(f!=null)
return f;
else {
return null;
}
}
#Override
protected void onPostExecute(FeedSource result){
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
rssItemList.setVerticalFadingEdgeEnabled(true);
if(doInBackground()==null){
TextView tv= (TextView) findViewById(R.id.textView2);
tv.setText("No internet Connection...");
}
else{
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, doInBackground().getFeed());
rssItemList.setAdapter(adapter);
}
}
}
#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_news, 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);
}
}
As #coelho pointed out, the FeedSource.getFeed() shouldn't be executed in the UI thread. You must now that the onPreExecute and onPostExecute methods are executed inside the UI thread, while the doInBackground method isn't.
Here's what you can do: in your AsyncTask class, add a private member: private List<RSSItem> result; (replace RSSItem here by the type of the collection returned by getFeed).
Then, update doInBackground:
FeedSource f = new HttpFeedSource();
if (f != null)
return f;
else {
this.result = f.getFeed(); // Execute getFeed in doInBackground
return null;
}
Then, in the onPostExecute method, you'll be able to use this private member as this:
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, this.result);
Here is the code:
private class rssfeedget extends AsyncTask<String, Void, List<RSSItem>> {
private List<RSSItem> result;
protected void onPreExecute() {
}
#Override
protected List<RSSItem> doInBackground(String... params) {
FeedSource f = new HttpFeedSource();
if(f.getFeed()==null)
return null;
else {
this.result = f.getFeed(); // Execute getFeed in doInBackground
return result;
}
}
#Override
protected void onPostExecute(List<RSSItem> result){
if(doInBackground()==null){
TextView tv= (TextView) findViewById(R.id.textView2);
tv.setText("No internet Connection...");
}
else{
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
rssItemList.setVerticalFadingEdgeEnabled(true);
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, this.result);
rssItemList.setAdapter(adapter);
}
}
}

Repeat AsyncTask on the next code

I have a code that only takes information from a web vía Jsoup and I want to refresh this information every second. I tried with all the code that I've found in Google and stackoverflow with no luck. Thank you very much in advance. [SOLVED]
Now I'm trying to send an array from MainActivity to another Activity called "Activity_allday" with Bundle and Intent when viewallday() function is called pressing the "btviewallday" button but with no luck. Any suggestions?
LogCat error: Could not find a method viewallday(View) in the activity class com.example.Chispa.MainActivity for onClick handler on view class android.widget.Button with id 'btviewallday'.
I've noticed that the error comes from receiving two values at viewallday(View view, Pair p). How can I receive the "Pair p" value in my viewallday function?
Here is the new app code:
[MainActivity]
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#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 class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view, Pair p) {
Intent intent = new Intent(this, Activity_allday.class);
Bundle bundle =new Bundle();
bundle.putStringArray("bar", p.bar);
intent.putExtras(bundle);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
try {
URL url= new URL("http://www.myweb.com");
Document doc = Jsoup.connect(url.toString()).get();
p.bar = getValuesGraph(doc);
p.values = getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
return p;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
[Activity_allday]
Public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_prices);
tvall = (TextView) findViewById(R.id.tvall);
Bundle bundle = this.getIntent().getExtras();
String[] bar=bundle.getStringArray("bar");
/*tvall.setText(bar[0]);*/
}
public void back (View view) {
finish();
}
}

Android Gallery issue, out of memory

The following code give java.lang.OutOfMemoryError : bitmap exceeds VM budget
i'm writing an app to swipe through a series of images , which are all full screen. I know i'm loading all images together thats whats causing the problem , but i dont know how to overcome this issue. Somebody please help .
package akash.gal;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class GalActivity extends Activity {
/** Called when the activity is first created. */
Integer imageids[]={R.drawable.one,R.drawable.two,R.drawable.three};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery=(Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context=c;
TypedArray a=obtainStyledAttributes(R.styleable.Gallery1);
itemBackground=a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground,0);
a.recycle();
}
public int getCount() {
// TODO Auto-generated method stub
return imageids.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView=new ImageView(context);
imageView.setImageResource(imageids[arg0]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
DisplayMetrics dm=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
imageView.setLayoutParams(new Gallery.LayoutParams(dm.widthPixels,dm.heightPixels));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
In Main Activity :--
public class Main extends Activity {
String mImagesPath;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImagesPath = this.getFilesDir().getParent() + "/images/";
createImagesDir(mImagesPath);
copyImagesToStorage();
loadGridView();
}
/**
* Method handles the logic for setting the adapter for the gridview
*/
private void loadGridView(){
GridView lLazyGrid = (GridView) this.findViewById(R.id.gridview);
try {
LazyImageAdapter lLazyAdapter = new LazyImageAdapter(this.getApplicationContext(),
null,
mImagesPath);
lLazyGrid.setAdapter(lLazyAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Copy images from assets to storage
*/
private void copyImagesToStorage(){
AssetManager lAssetManager = getAssets();
String[] lFiles = null;
String lTag = "copyImageFail";
try {
// get all of the files in the assets directory
lFiles = lAssetManager.list("");
} catch (IOException e) {
Log.e(lTag, e.getMessage());
}
for(int i=0; i<lFiles.length; i++) {
// We have a file to copy
try {
// copy the file
copyFile(lFiles[i], mImagesPath + lFiles[i]);
} catch(Exception e) {
Log.e(lTag, e.getMessage());
}
}
}
/**
* Method copies the contents of one stream to another
* #param aIn stream to copy from
* #param aOut stream to copy to
* #throws IOException
*/
private void copyFile(String aIn, String aOut) throws IOException {
byte[] lBuffer = new byte[1024];
int lRead;
final int lOffset = 0;
// create an in and out stream
InputStream lIn = getAssets().open(aIn);
OutputStream lOut = new FileOutputStream(aOut);
// Copy contents while there is data
while((lRead = lIn.read(lBuffer)) != -1){
lOut.write(lBuffer, lOffset, lRead);
}
// clean up after our streams
lIn.close();
lIn = null;
lOut.flush();
lOut.close();
lOut = null;
}
/**
* Create the directory specified at aPath if it does not exist
* #param aPath directory to check for and create
*/
private void createImagesDir(String aPath){
File lDir = new File(aPath);
if(!lDir.exists()){
lDir.mkdir();
}
}
}
=====================================
In ImageLoader Class :
public class ImageLoader extends Thread {
public interface ImageLoadListener {
void handleImageLoaded(ViewSwitcher aViewSwitcher, ImageView aImageView, Bitmap aBitmap);
}
private static final String TAG = ImageLoader.class.getSimpleName();
ImageLoadListener mListener = null;
private Handler handler;
/**
* Image loader takes an object that extends ImageLoadListener
* #param lListener
*/
ImageLoader(ImageLoadListener lListener){
mListener = lListener;
}
#Override
public void run() {
try {
// preparing a looper on current thread
// the current thread is being detected implicitly
Looper.prepare();
// Looper gets attached to the current thread by default
handler = new Handler();
Looper.loop();
// Thread will start
} catch (Throwable t) {
Log.e(TAG, "ImageLoader halted due to a error: ", t);
}
}
/**
* Method stops the looper and thus the thread
*/
public synchronized void stopThread() {
// Use the handler to schedule a quit on the looper
handler.post(new Runnable() {
public void run() {
// This runs on the ImageLoader thread
Log.i(TAG, "DownloadThread loop quitting by request");
Looper.myLooper().quit();
}
});
}
/**
* Method queues the image at path to load
* Note that the actual loading takes place in the UI thread
* the ImageView and ViewSwitcher are just references for the
* UI thread.
* #param aPath - Path where the bitmap is located to load
* #param aImageView - The ImageView the UI thread will load
* #param aViewSwitcher - The ViewSwitcher that needs to display the imageview
*/
public synchronized void queueImageLoad(
final String aPath,
final ImageView aImageView,
final ViewSwitcher aViewSwitcher) {
// Wrap DownloadTask into another Runnable to track the statistics
handler.post(new Runnable() {
public void run() {
try {
synchronized (aImageView){
// make sure this thread is the only one performing activities on
// this imageview
BitmapFactory.Options lOptions = new BitmapFactory.Options();
lOptions.inSampleSize = 1;
Bitmap lBitmap = BitmapFactory.decodeFile(aPath, lOptions);
//aImage.setImageBitmap(lBitmap);
// Load the image here
signalUI(aViewSwitcher, aImageView, lBitmap);
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
/**
* Method is called when the bitmap is loaded. The UI thread adds the bitmap to the imageview.
* #param aViewSwitcher - The ViewSwitcher that needs to display the imageview
* #param aImageView - The ImageView the UI thread will load
* #param aImage - The Bitmap that gets loaded into the ImageView
*/
private void signalUI(
ViewSwitcher aViewSwitcher,
ImageView aImageView,
Bitmap aImage){
if(mListener != null){
// we have an object that implements ImageLoadListener
mListener.handleImageLoaded(aViewSwitcher, aImageView, aImage);
}
}
}
======================================
IN LazyImageAdapter :
public class LazyImageAdapter extends BaseAdapter implements ImageLoadListener {
private static final int PROGRESSBARINDEX = 0;
private static final int IMAGEVIEWINDEX = 1;
private Context mContext = null;
private OnClickListener mItemClickListener;
private Handler mHandler;
private ImageLoader mImageLoader = null;
private File mDirectory;
/**
* Lazy loading image adapter
* #param aContext
* #param lClickListener click listener to attach to each item
* #param lPath the path where the images are located
* #throws Exception when path can't be read from or is not a valid directory
*/
public LazyImageAdapter(
Context aContext,
OnClickListener lClickListener,
String lPath
) throws Exception {
mContext = aContext;
mItemClickListener = lClickListener;
mDirectory = new File(lPath);
// Do some error checking
if(!mDirectory.canRead()){
throw new Exception("Can't read this path");
}
else if(!mDirectory.isDirectory()){
throw new Exception("Path is a not a directory");
}
mImageLoader = new ImageLoader(this);
mImageLoader.start();
mHandler = new Handler();
}
#Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
// stop the thread we started
mImageLoader.stopThread();
}
public int getCount() {
return mDirectory.listFiles().length;
}
public Object getItem(int aPosition) {
String lPath = null;
File []lFiles = mDirectory.listFiles();
if(aPosition < lFiles.length){
lPath = mDirectory.listFiles()[aPosition].getAbsolutePath();
}
return lPath;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int aPosition, View aConvertView, ViewGroup parent) {
final ViewSwitcher lViewSwitcher;
String lPath = (String)getItem(aPosition);
// logic for conserving resources see google video on making your ui fast
// and responsive
if (null == aConvertView) {
lViewSwitcher = new ViewSwitcher(mContext);
lViewSwitcher.setPadding(8, 8, 8, 8);
ProgressBar lProgress = new ProgressBar(mContext);
lProgress.setLayoutParams(new ViewSwitcher.LayoutParams(80, 80));
lViewSwitcher.addView(lProgress);
ImageView lImage = new ImageView(mContext);
lImage.setLayoutParams(new ViewSwitcher.LayoutParams(100, 100));
lViewSwitcher.addView(lImage);
// attach the onclick listener
lViewSwitcher.setOnClickListener(mItemClickListener);
} else {
lViewSwitcher = (ViewSwitcher) aConvertView;
}
ViewTagInformation lTagHolder = (ViewTagInformation) lViewSwitcher
.getTag();
if (lTagHolder == null ||
!lTagHolder.aImagePath.equals(lPath)) {
// The Tagholder is null meaning this is a first time load
// or this view is being recycled with a different image
// Create a ViewTag to store information for later
ViewTagInformation lNewTag = new ViewTagInformation();
lNewTag.aImagePath = lPath;
lViewSwitcher.setTag(lNewTag);
// Grab the image view
// Have the progress bar display
// Then queue the image loading
ImageView lImageView = (ImageView) lViewSwitcher.getChildAt(1);
lViewSwitcher.setDisplayedChild(PROGRESSBARINDEX);
mImageLoader.queueImageLoad(lPath, lImageView, lViewSwitcher);
}
return lViewSwitcher;
}
public void handleImageLoaded(
final ViewSwitcher aViewSwitcher,
final ImageView aImageView,
final Bitmap aBitmap) {
// The enqueue the following in the UI thread
mHandler.post(new Runnable() {
public void run() {
// set the bitmap in the ImageView
aImageView.setImageBitmap(aBitmap);
// explicitly tell the view switcher to show the second view
aViewSwitcher.setDisplayedChild(IMAGEVIEWINDEX);
}
});
}
}
/**
* View holder pattern as described in google sample code
* we may want to add more attributes to this if the path was
* say being stored in a sqlite database
* #author bacaj
*/
class ViewTagInformation {
String aImagePath;
}

Categories

Resources