online azure table is working but offline is not - android

I am trying offline sync in my azure mobile app but it always returns null pointer.I been debugging to reach the root of error for 3 days but cannot figure it out.Any help will be highly appreciated.Every time i debug i get this error,I have followed the same steps provided by Microsoft azre.
My class is
public class User {
#com.google.gson.annotations.SerializedName("id")
private String mId;
#com.google.gson.annotations.SerializedName("phonenumber")
private String mText;
#com.google.gson.annotations.SerializedName("email")
private boolean mComplete;
#com.google.gson.annotations.SerializedName("name")
private String mName;
public User() {
}
#Override
public String toString() {
return getText();
}
public User(String text, String id) {
this.setText(text);
this.setId(id);
}
public String getText() {
return mText;
}
public final void setText(String text) {
mText = text;
}
public String getId() {
return mId;
}
public final void setId(String id) {
mId = id;
}
public boolean isComplete() {
return mComplete;
}
public void setComplete(boolean complete) {
mComplete = complete;
}
#Override
public boolean equals(Object o) {
return o instanceof User && ((User) o).mId == mId;
}}
and my activity is
public class ToDoActivity extends Activity {
/**
* Mobile Service Client reference
*/
private MobileServiceClient mClient;
//Offline Sync
/**
* Mobile Service Table used to access and Sync data
*/
private MobileServiceSyncTable<User> mToDoTable;
/**
* Adapter to sync the items list with the view
*/
private ToDoItemAdapter mAdapter;
/**
* EditText containing the "New To Do" text
*/
private EditText mTextNewToDo;
/**
* Progress spinner to use for table operations
*/
private ProgressBar mProgressBar;
/**
* Initializes the activity
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
mProgressBar = (ProgressBar) findViewById(R.id.loadingProgressBar);
// Initialize the progress bar
mProgressBar.setVisibility(ProgressBar.GONE);
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"https://housewrench.azurewebsites.net",
this).withFilter(new ProgressFilter());
// Extend timeout from default of 10s to 20s
mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() {
#Override
public OkHttpClient createOkHttpClient() {
OkHttpClient client = new OkHttpClient();
client.setReadTimeout(20, TimeUnit.SECONDS);
client.setWriteTimeout(20, TimeUnit.SECONDS);
return client;
}
});
// Get the Mobile Service Table instance to use
// mToDoTable = mClient.getTable(ToDoItem.class);
// mUserTable = mClient.getTable(User.class);
// Offline Sync
mToDoTable = mClient.getSyncTable("User", User.class);
//Init local storage
initLocalStore().get();
mTextNewToDo = (EditText) findViewById(R.id.textNewToDo);
// Create an adapter to bind the items with the view
mAdapter = new ToDoItemAdapter(this, R.layout.row_list_to_do);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(mAdapter);
// Load the items from the Mobile Service
refreshItemsFromTable();
} catch (MalformedURLException e) {
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
} catch (Exception e){
createAndShowDialog(e, "Error");
}
}
/**
* Initializes the activity menu
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Select an option from the menu
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_refresh) {
refreshItemsFromTable();
}
return true;
}
/**
* Mark an item as completed
*
* #param item
* The item to mark
*/
public void checkItem(final ToDoItem item) {
if (mClient == null) {
return;
}
// Set the item as completed and update it in the table
item.setComplete(true);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
checkItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (item.isComplete()) {
mAdapter.remove(item);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Mark an item as completed in the Mobile Service Table
*
* #param item
* The item to mark
*/
public void checkItemInTable(ToDoItem item) throws ExecutionException, InterruptedException {
//mToDoTable.update(item).get();
}
/**
* Add a new item
*
* #param view
* The view that originated the call
*/
public void addItem(View view) {
if (mClient == null) {
return;
}
// Create a new item
final ToDoItem item = new ToDoItem();
item.setText(mTextNewToDo.getText().toString());
item.setComplete(false);
// Insert the new item
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final ToDoItem entity = addItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!entity.isComplete()){
mAdapter.add(entity);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
mTextNewToDo.setText("");
}
/**
* Add an item to the Mobile Service Table
*
* #param item
* The item to Add
*/
public ToDoItem addItemInTable(ToDoItem item) throws ExecutionException, InterruptedException {
// ToDoItem entity = mToDoTable.insert(item).get();
return item;
}
/**
* Refresh the list with the items in the Table
*/
private void refreshItemsFromTable() {
// Get the items that weren't marked as completed and add them in the
// adapter
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
//final List<User> results = refreshItemsFromMobileServiceTable();
//Offline Sync
final List<User> results = refreshItemsFromMobileServiceTableSyncTable();
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.clear();
for (User item : results) {
//mAdapter.add(item);
}
}
});
} catch (final Exception e){
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Refresh the list with the items in the Mobile Service Table
*/
private List<User> refreshItemsFromMobileServiceTable() throws
ExecutionException, InterruptedException {
return mUserTable.where().field("name").
eq(val("noor")).execute().get();
}
//Offline Sync
/**
* Refresh the list with the items in the Mobile Service Sync Table
*/
private List<User> refreshItemsFromMobileServiceTableSyncTable() throws
ExecutionException, InterruptedException {
//sync the data
sync().get();
Query query = QueryOperations.field("phonenumber").
eq(val(false));
return mToDoTable.read(query).get();
}
/**
* Initialize local storage
* #return
* #throws MobileServiceLocalStoreException
* #throws ExecutionException
* #throws InterruptedException
*/
private AsyncTask<Void, Void, Void> initLocalStore() throws MobileServiceLocalStoreException, ExecutionException, InterruptedException {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
if (syncContext.isInitialized())
return null;
SQLiteLocalStore localStore = new SQLiteLocalStore(mClient.getContext(), "MyStore", null, 1);
Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
tableDefinition.put("id", ColumnDataType.String);
tableDefinition.put("phonenumber", ColumnDataType.String);
tableDefinition.put("name", ColumnDataType.String);
tableDefinition.put("email", ColumnDataType.String);
localStore.defineTable("User", tableDefinition);
SimpleSyncHandler handler = new SimpleSyncHandler();
syncContext.initialize(localStore, handler).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
//Offline Sync
/**
* Sync the current context and the Mobile Service Sync Table
* #return
*/
private AsyncTask<Void, Void, Void> sync() {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
mToDoTable.pull(null).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialogFromTask(final Exception exception, String title) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createAndShowDialog(exception, "Error");
}
});
}
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialog(Exception exception, String title) {
Throwable ex = exception;
if(exception.getCause() != null){
ex = exception.getCause();
}
createAndShowDialog(ex.getMessage(), title);
}
/**
* Creates a dialog and shows it
*
* #param message
* The dialog message
* #param title
* The dialog title
*/
private void createAndShowDialog(final String message, final String title) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
/**
* Run an ASync task on the corresponding executor
* #param task
* #return
*/
private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
return task.execute();
}
}
private class ProgressFilter implements ServiceFilter {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) {
final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
});
ListenableFuture<ServiceFilterResponse> future = nextServiceFilterCallback.onNext(request);
Futures.addCallback(future, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable e) {
resultFuture.setException(e);
}
#Override
public void onSuccess(ServiceFilterResponse response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.GONE);
}
});
resultFuture.set(response);
}
});
return resultFuture;
}
}
}

Based on your code, it seems that you have followed the Azure mobile apps quickstart sample for android and adjusted the ToDoItem to your User. I noticed that you did not set properly getter and setter for your name column, and the definition for your email column is String, but your assigned it to the boolean mComplete.
I would recommend you check the offline sync against your ToDoItem table is correctly. And you'd better set breakpoints to the catch code block to see which task throws the exception and check the relevant code to narrow this issue. If you could not solve this issue, you could update your question with the specific code line(s) that threw the exception and the detailed exception info for us to troubleshoot this issue.

Related

SQL query with listview

I am busy with an application where i am getting data from my azure database with sql and storing it in an array. I created a separate class where i get my data and my main activity connects to this class and then displays it.
Here is my getData class:
public class GetData {
Connection connect;
String ConnectionResult = "";
Boolean isSuccess = false;
public List<Map<String,String>> doInBackground() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr=new ConnectionHelper();
connect =conStr.connectionclass(); // Connect to database
if (connect == null) {
ConnectionResult = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("NAME",rs.getString("RAIL_NAME"));
datanum.put("PRICE",rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE",rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER",rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE",rs.getString("RAIL_SIZE"));
data.add(datanum);
}
ConnectionResult = " successful";
isSuccess=true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
ConnectionResult = ex.getMessage();
}
return data;
}
}
And in my Fragmentactivity.java I simply just call the class as shown here:
List<Map<String,String>> MyData = null;
GetValence mydata =new GetValence();
MyData= mydata.doInBackground();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_valence, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
My problem comes when I want to include the onPreExecute and onPostExecute because I am relatively new to android studio and I do not know where to put the following lines of code:
#Override
protected void onPreExecute() {
ProgressDialog progress;
progress = ProgressDialog.show(MainActivity.this, "Synchronising", "Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
}
You need to get the data from your azure database using a background service or AsyncTask. However, you are defining a class GetData which does not extend AsyncTask and hence the whole operation is not asynchronous. And I saw you have implemented doInBackground method which is not applicable here as you are not extending AsyncTask. I would suggest an implementation like the following.
You want to get some data from your azure database and want to show them in your application. In these kind of situations, you need to do this using an AsyncTask to call the server api to get the data and pass the data to the calling activity using an interface. Let us have an interface like the following.
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
Now from your Activity while you want to get the data through an web service call, i.e. AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
public HttpResponseListener mHttpResponseListener;
private final Context mContext;
HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
this.mContext = mContext;
this.mHttpResponseListener = listener;
}
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
// Your implementation of getting data from your server
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
#Override
protected void onCancelled() {
mHttpResponseListener.httpResponseReceiver(null);
}
}
Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
// ... Other code and overriden functions
public void callAsyncTaskForGettingData() {
// Pass the listener here
HttpRequestAsyncTask getDataTask = new HttpRequestGetAsyncTask(
YourActivity.this, this);
getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void httpResponseReceiver(String result) {
// Get the response callback here
// Do your changes in UI elements here.
}
}
To read more about how to use AsyncTask, you might consider having a look at here.

Asynchronous call to server being blocked by bluetooth LE Scan

I have an Activity which constructs a RESTManager class (used to make an asynchronous call to the server and return data to the Activity).
However, after I construct my RESTManager and call the server using
//Retrieve data from server
RESTManager m = new RESTManager(this,getApplicationContext());
//Set the data list
m.delegate=this;
m.retrieveRoomData();
the server call does not go through until I turn off bluetooth scanning.
However, I start my bluetooth scan immediately after the RESTManager as such:
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.setBackgroundScanPeriod(1100l);
beaconManager.setBackgroundBetweenScanPeriod(100l);
beaconManager.setForegroundScanPeriod(1100l);
beaconManager.setForegroundBetweenScanPeriod(100l);
//Set the custom BeaconLayout for iBeacons
if (myPref.getBoolean("layoutSet", true)) {
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"));
backgroundPowerSaver = new BackgroundPowerSaver(this);
Log.v("Beacon Layout", "Beacon Layout Set");
myPref.edit().putBoolean("layoutSet", false).apply();
myPref.edit().commit();
}
beaconManager.bind(this);
I am not getting any error.
Is there any reason why my AsyncTask from RESTManager would hang from the bluetooth scans?
Relevant code:
RESTManager class
public class RESTManager {
private DateTime lastUpdate = DateTime.now();
public AsyncResponse delegate=null;
private SharedPreferences mPrefs;
private SharedPreferences.Editor preferenceEditor;
private ArrayList<RoomData> roomDataList = new ArrayList<RoomData>();
private ArrayList<MeetingData> meetingDataList = new ArrayList<MeetingData>();
private Activity currentActivity;
private Context context;
public RESTManager(Activity currentActivity, Context context) {
this.currentActivity = currentActivity;
this.context = context;
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
//Todo update meeting data logic
public ArrayList<MeetingData> retrieveMeetingDataFromServer() {
return null;
}
public void retrieveRoomData() {
new CallServerForRoomData().execute();
}
//TODO add timestamping logic.
private class CallServerForRoomData extends AsyncTask<String, Void, String> {
String myJsonData = "";
#Override
protected String doInBackground(String... params) {
//If the data isn't cached, call the server.
if (!mPrefs.contains("RoomData")) {
try {
setupHttpClient();
HttpClient myClient = new HttpClient(RequestMethod.GET, "http://10.184.46.217:9012/v1/rooms", new HttpHeaders(), null, null);
myClient.connect();
HttpResponse mR = myClient.processResponse();
myJsonData = mR.getServerResponseAsString();
System.out.println(myJsonData);
preferenceEditor = mPrefs.edit();
preferenceEditor.putString("RoomData", myJsonData);
preferenceEditor.commit();
setRoomDataList(convertRoomDataJson(myJsonData));
return "server";
} catch (HttpClientException e) {
e.printStackTrace();
}
}
//If it is cached, retrieve the data locally.
else {
setRoomDataList(convertRoomDataJson(mPrefs.getString("RoomData", "NULL")));
return "local";
}
return "Done";
}
protected void onPostExecute(final String result) {
delegate.dataFinishedRetrieving(getRoomDataList());
// setRoomDataList(convertRoomDataJson(myJsonData));
currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Data retrieved on " + result + " storage", Toast.LENGTH_SHORT).show();
}
});
}
}
/**
* AsyncTask for retrieving a room's meeting data.
* Pass in the room's unique identifier as a parameter of the execute method.
*/
//TODO add timestamping logic
private class CallServerForMeetingData extends AsyncTask<String, Void, String> {
String myJsonData = "";
#Override
protected String doInBackground(String... params) {
try {
setupHttpClient();
HttpClient myClient = new HttpClient(RequestMethod.GET, "http://10.184.146.217:9012/v1/room/" + params[0] + "/schedule", new HttpHeaders(), null, null);
myClient.connect();
HttpResponse mR = myClient.processResponse();
myJsonData = mR.getServerResponseAsString();
} catch (HttpClientException e) {
e.printStackTrace();
}
//Set the converted MeetingData to the RoomData object
for (RoomData e : roomDataList) {
if (e.getObjectId() == params[0]) {
e.setMeetingData(convertMeetingDataJson(myJsonData));
}
}
return "Done";
}
}
//Initializes the HTTPClient and attaches it to the application lifecycle.
public void setupHttpClient() {
HttpCacheManager.init(Application.getAppContext());
}
public ArrayList<MeetingData> convertMeetingDataJson(String JsonData) {
final Gson gson = initCustomGSON();
Type MeetingDataListType = null;
if (JsonData != "") {
MeetingDataListType = new TypeToken<ArrayList<MeetingData>>() {
}.getType();
}
return (gson.fromJson(JsonData, MeetingDataListType));
}
public ArrayList<RoomData> convertRoomDataJson(String JsonData) {
final Gson gson = initCustomGSON();
Type RoomDataListType = null;
if (!JsonData.equals("")) {
RoomDataListType = new TypeToken<ArrayList<RoomData>>() {
}.getType();
roomDataList = (gson.fromJson(JsonData, RoomDataListType));
}
roomDataList = (gson.fromJson(JsonData, RoomDataListType));
for (RoomData e : roomDataList) {
Log.v("RoomData name", e.getName());
Log.v("RoomData roomId", e.getObjectId());
//Log.v("RoomData imageUrl", e.getImageUrl());
if (e.getBeacons() != null) {
Log.v("Number of beacons", e.getBeacons().toString());
}
}
return roomDataList;
}
/**
* Initializes the GSON Json Decoder with the custom JodaTime serializers.
*
* #return
*/
public Gson initCustomGSON() {
final GsonBuilder builder = new GsonBuilder();
JodaTimeConverters converter = new JodaTimeConverters();
converter.registerAll(builder);
return builder.create();
}
public ArrayList<RoomData> getRoomDataList() {
return roomDataList;
}
public void setRoomDataList(ArrayList<RoomData> roomDataList) {
this.roomDataList = roomDataList;
}
public void setMeetingDataListForRoom(RoomData whichRoom) {
new CallServerForMeetingData().execute(whichRoom.getObjectId());
}
}

How to refresh view pager in android?

I have some images in my view pager and i am deleting images from delete button,but after deleting image i want to refresh view pager and and want to display remaining image in my application can any one what is mistake?
public class PhotoView extends Activity{
private Button btn;
private String User_IDs;
private String total;
private String max;
ArrayList<Integer> userImgidArrayList;
ArrayList<String> userstatusArrayList;
ArrayList<String> userphotoArrayList;
private ImageView imageView;
private Button btndelete;
private Button btnsetprofilepic;
int singlepicid;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String DELT_SETPRO_URL = "my url";
private static final String DELT_SETPRO_STATUS = "status";
private static final String DELT_SETPRO_MSG = "msg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoview);
User_IDs=this.getIntent().getStringExtra("id");
System.out.println("photo upload view user id"+User_IDs);
IMAGE_URL="my url"+User_IDs;
total=this.getIntent().getStringExtra("totals");
System.out.println("photo total "+total);
max=this.getIntent().getStringExtra("maxs");
System.out.println("photo maximum "+max);
userImgidArrayList = getIntent().getIntegerArrayListExtra("photoid");
System.out.println(userImgidArrayList);
userstatusArrayList=getIntent().getStringArrayListExtra("imgstatus");
System.out.println(userstatusArrayList);
userphotoArrayList=getIntent().getStringArrayListExtra("pics");
System.out.println(userphotoArrayList);
for(int i=0;i< userImgidArrayList.size();i++)
{
singlepicid=userImgidArrayList.get(i);
System.out.println(singlepicid);
}
for(int i=0;i< userphotoArrayList.size();i++)
{
String singleimage=userphotoArrayList.get(i);
System.out.println(singleimage);
}
for(int i=0;i< userstatusArrayList.size();i++)
{
String singlestatus=userstatusArrayList.get(i);
System.out.println(singlestatus);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
imageView = (ImageView) findViewById(R.id.full_image_views);
btn=(Button)findViewById(R.id.goforupload);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent=new Intent(getApplicationContext(),PhotoUpload.class);
intent.putExtra("id", User_IDs);
startActivity(intent);
}
});
btndelete=(Button)findViewById(R.id.deleteimage);
btndelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
singlepicid = userImgidArrayList.get(viewPager.getCurrentItem());
new AttemptLogin().execute();
userphotoArrayList.remove(viewPager.getCurrentItem());
// adapter.notifyDataSetChanged();
viewPager.getAdapter().notifyDataSetChanged();
}
});
btnsetprofilepic=(Button)findViewById(R.id.setprofilepic);
btnsetprofilepic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class ImageAdapter extends PagerAdapter {
Context context;
ImageAdapter(Context context)
{
this.context=context;
}
#Override
public int getCount() {
return userphotoArrayList.size();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
Picasso.with(context).load(userphotoArrayList.get(position)).into(imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public int getItemPosition(Object object) {
viewPager.setAdapter(adapter);
return POSITION_NONE;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PhotoView.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
//Check for success tag
String btnmethod=btndelete.getTag().toString();
/*String val=null;
singlepicid=Integer.parseInt(val);*/
Looper.prepare();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_login_id", User_IDs));
params.add(new BasicNameValuePair("method", btnmethod));
params.add(new BasicNameValuePair("user_photo_id", String.valueOf(singlepicid)));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
DELT_SETPRO_URL, "POST", params);
System.out.println(params);
//check your log for json response
Log.d("Processing", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(DELT_SETPRO_STATUS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
}}
class LoadImages extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
String photoid;
int userPhotoId;
String userstatus;
String uploadedpics;
#Override
protected void onPreExecute() {
super.onPreExecute();
prDialog = new ProgressDialog(PhotoView.this);
prDialog.setMessage("Refreshing...");
prDialog.setIndeterminate(false);
prDialog.setCancelable(false);
prDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(IMAGE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
jsonobj = new JSONObject(jsonStr);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(IMAGE_USERLOGIN_ID, jsonobj.getString(IMAGE_USERLOGIN_ID));
map.put(IMAGE_TOTAL_PHOTO,jsonobj.getString(IMAGE_TOTAL_PHOTO));
map.put(IMAGE_MAX_UPLOAD, jsonobj.getString(IMAGE_MAX_UPLOAD));
final String totalphota = jsonobj.getString("user_total_photo");
Log.d("Value: ", "> " + totalphota);
final String maximumphota = jsonobj.getString("max_upload_photo");
Log.d("Value: ", "> " + maximumphota);
userImgidArrayList = new ArrayList<Integer>();
image_list = (JSONArray) jsonobj.get("image_list");
for(int i=0;i< image_list.length();i++)
{
JSONObject imageListItem = image_list.getJSONObject(i);
userPhotoId = imageListItem.getInt("user_photo_id");
userImgidArrayList.add(userPhotoId);
Log.d("mylog", "i ="+i+" and user_photo_id =" + userPhotoId);
}
userstatusArrayList = new ArrayList<String>();
image_list = (JSONArray) jsonobj.get("image_list");
for(int i=0;i< image_list.length();i++)
{
JSONObject statusListItem = image_list.getJSONObject(i);
userstatus = statusListItem.getString("status");
userstatusArrayList.add(userstatus);
Log.d("mylog", "i ="+i+" and status =" + userstatus);
}
userphotoArrayList = new ArrayList<String>();
image_list = (JSONArray) jsonobj.get("image_list");
for(int i=0;i< image_list.length();i++)
{
JSONObject photoListItem = image_list.getJSONObject(i);
uploadedpics=photoListItem.getString("photo");
userphotoArrayList.add(uploadedpics);
Log.d("mylog", "i ="+i+" and photo =" + uploadedpics);
}
} catch (JSONException e) {
e.printStackTrace();
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
if (prDialog.isShowing())
prDialog.dismiss();
}
}
Alternatively.. you can Refresh your activity..
try this
On click refresh button
finish();
startActivity(getIntent());
btndelete=(Button)findViewById(R.id.deleteimage);
btndelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
userphotoArrayList.remove(viewPager.getCurrentItem())
adapter.notifyDataSetChanged();
}
});
and also in your adapter:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Rewrite all my answer:
Firstly , let's see the usage of AsyncTask, here is important functions:
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {#link #execute}
* by the caller of this task.
*
* This method can call {#link #publishProgress} to publish updates
* on the UI thread.
*
* #param params The parameters of the task.
*
* #return A result, defined by the subclass of this task.
*
* #see #onPreExecute()
* #see #onPostExecute
* #see #publishProgress
*/
protected abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {#link #doInBackground}.
*
* #see #onPostExecute
* #see #doInBackground
*/
protected void onPreExecute() {
}
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param result The result of the operation computed by {#link #doInBackground}.
*
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/
#SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
Now , let's see what have you done in AsyncTask , Notice I have change the template of AsyncTask:
class AttemptLogin extends AsyncTask<String, String, int> {
#Override
protected void onPreExecute() {
//Here you have show a dialog with loading message, that's great.
}
#Override
protected int doInBackground(String...args) {
//Here you send http request to delete data on server, and receive response from it.
JSONObject json = jsonParser.makeHttpRequest (
DELT_SETPRO_URL, "POST", params);
System.out.println(params);
//check your log for json response
Log.d("Processing", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
//That's all right so far , bug you haven't confirm whether the server have delete the data you want to .
//So you should write some code to check this
if(msg.equals("Succ")//Just for example
{
//Here you have check the data is already delete by server
//Now you can delete the data store in your code not the server
return viewPager.getCurrentItem();//return the index of viewPager you want to delete to onPostExecute
}
else
{
//something wrong with server , so you shouldn't delete anything
return -1; //Just return -1 let onPostExecute know no one need to be deleted.
}
}
#Override
protected void onPostExecute(int index) {
//Here is in UI Thread
if(index != -1) {
userphotoArrayList.remove(index)//Delete the data with this index
//Now your data have changed but the view haven't changed , you should call notifyDataSetChanged
viewPager.getAdapter().notifyDataSetChanged();
}
else {
//You should let User know he or she delete photo failed
Toast.makeText(PhotoView.this, "Delete failed", Toash.LENGTH_SHORT).show();
}
}
}
And , don't not just copy my code , there is a lot of assumption。

Refresh json thread to parse data on specific intervals

Ideally I want to implement
Method level synchronization where whole method is synchronized every 1minute
Not
Block level synchronization where only some set of statements are synchronized
But I don't know why when my new runnable handler execute the method at the set interval. It parses unchanged json data again and again populating my listview in a redundant manner.
How can I implement a handler that will only parse data from json that has changed/updated from previous 60seconds, without repeating data on list view?
private class MyAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RegionListActivity.this);
dialog.setMessage("Please wait..");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String url_structure = GlobalData.MAIN_URL + sessionId
+ "/user_session/?sections=app-basic&company_id="
+ companyId;
String response_structure = CallWebService
.getResponseOfUrl(url_structure);
parseRegionList(response_structure);
String url_unit = GlobalData.MAIN_URL + sessionId
+ "/reporting/system/unit_status/?sections&company_id="
+ companyId;
String response_unit = CallWebService.getResponseOfUrl(url_unit);
parseUnitStatus(response_unit);
return null;
}
#SuppressWarnings("null")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
if (!alRegions.isEmpty() && !alParents.isEmpty()) {
expandableAdapter = new ExpandableListAdapter(
RegionListActivity.this, alParents);
lvExpandableRL.setAdapter(expandableAdapter);
GlobalData.alAssetsGlobal = hashMapAssets;
GlobalData.alComponetsGlobal = hashMapComponents;
}
else {
lvExpandableRL.setVisibility(View.GONE);
tvNoRecordsRL.setVisibility(View.VISIBLE);
}
tvCompanyNameRL.setText(GlobalData.COMPANY_NAME);
tvActiveAlarmsRL.setText(GlobalData.ACTIVE_ALARMS);
tvUnitsOfflineRL.setText(GlobalData.OFFLINE_COUNT);
/*
* try { if(alUnitNumber.size()>0 && alUnitNumber != null) {
* al_unit_snumber=alUnitNumber;
* lvUnitsOffline.setVisibility(View.VISIBLE); adapter= new
* UnitListAdapter(RegionListActivity.this, alUnitNumber);
* lvUnitsOffline.setAdapter(adapter); } else {
* lvUnitsOffline.setVisibility(View.GONE);
* tvNoRecordsUnitListOffline.setVisibility(View.VISIBLE); } } catch
* (Exception e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*
* if(alUnitStatus.size()>0 && alUnitStatus != null)
*
* alUnitStatus=(ArrayList<DataUnits>)getArguments()
* .getSerializable(WebElement.RECORDS); if(alUnitStatus.size()>0 &&
* alUnitStatus != null) { al_unit_snumber=alUnitNumber;
* lvUnitsOffline.setVisibility(View.VISIBLE); adapter= new
* UnitListAdapter(RegionListActivity.this, alUnitStatus);
* lvUnitsOffline.setAdapter(adapter); } else {
* lvUnitsOffline.setVisibility(View.GONE);
* tvNoRecordsUnitListOffline.setVisibility(View.VISIBLE); }
*/
}
new Handler().postDelayed(new Runnable() {
public void run() {
// call JSON methods here
new MyAsyncTask().execute();
}
}, 60000);
}

How to send Progress from library on Android?

I have a project: myApp
these files...
- myFragment.java.
- myDialogFragment.java.
- myAsyncTask.java
I have a project: myLibrary
This project "is Library" of "myApp"
I have...
- myMethodsToUpload.java
One of these methods, have a While bucle for write the file on php server.
Everything works like magic! :)
and the reason for the file structure is to make the library reusable.
but...
How can I send the increments of a value inside of this While bucle, to myAsyncTask.java?
Considering that...
what I want to do... is to make "myMethodsToUpload.java", reusable.
Some code...
myFragment.java
myDialogFragment df = new myDialogFragment();
df.setMyThings(new myAsynctask(), myParameters);
df.setTargetFragment(this, 0);
df.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
.
myDialogFragment.java
public class myDialogFragment extends DialogFragment {
myAsyncTask async;
public void setMyThings(myAsynctask inAsynctask, String[] inArray){
async = inAsynctask;
async.sendFragment(this);
parameters = inArray;
}
//...
//Only called from "myAsyncTask.java"
public void updateFromAsyncTask(Integer porcent){
progressbar.setProgress(porcent);
}
//...
}
.
myAsyncTask.java
public class myAsynctask extends AsyncTask<String, Integer, String> {
void sendFragment(myDialogFrament inFragment){
myDialogFrament = inFragment;
}
//...
#Override
protected String doInBackground(String... inArray) {
String urlPHP = inArray[0];
String pathImg = inArray[1];
String paramValue = inArray[2];
String msj = "";
try {
methodsToUpload up = new methodsToUpload(urlPHP);
up.connectNow();
up.insertFile(pathImg);
up.insertParams("pName", paramValue);
up.insertFinish();
msj = up.coonectClose();
} catch (Exception e) {
e.printStackTrace();
}
return msj;
}
//Called from "myMethods.java"
public void updateFromAsyncTask(int porcent){
publishProgress(porcent);
}
#Override
protected void onProgressUpdate(Integer... inPorcent) {
if(myDialogFragment == null){
return;
}
myDialogFragment.updateFromAsyncTask(inPorcent[0]);
}
}
.
myMethodsToUpload.java
public class myMethodsToUpload {
//...
public myMethodsToUpload(String url_in){
this.url = url_in;
}
public void insertFile(String path) throws Exception {
//...
//...
while (bytesRead > 0) {
salidaStream.write(buffer, 0, bufferSize);
sendedPorcent += bytesRead;
completedPorcent = (int) (sendedPorcent * 100 / fileSize);
//This line doesn't work...
//because myAsyncTask.java, is in another project.
myAsyncTask.updateFromAsyncTask(completedPorcent);
bytesAvailable = archivoStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = archivoStream.read(buffer, 0, bufferSize);
}
//...
//...
}
}
.
I've already tried...
"MyLibrary" -> propeties -> java build path -> projects -> add -> Project(myApp)
but...
throws me errors:
W/System.err(32469): at java.util.concurrent.FutureTask.run(FutureTask.java:237)...
ThreadPoolExecutor.runworker...
etc.
And, in the status bar of eclipse appears every moment "Building Workspace (X%)"
I'm a newbie, but I think the error happens because "MyLibrary" is Library of "MyApp", and I'm trying use "java build path".
So... how can I resolve this?, I'm lost!!!
sorry by my english... thanks in advance! :)
Here is a simple exemple :
Your AsyncTask class :
private CallBack mCallback;
public static interface CallBack {
public void updateValue(int value);
}
public void setCallBack(CallBack callBack){
this.mCallBack = callBack;
}
#Override
protected void onProgressUpdate(Integer... inPorcent) {
mCallback.updateValue(inPorcent[0].intValue());
}
Your fragment class :
public class Fragment extends Fragment implements Callback {
private AsyncTask yourAsyncTask;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yourAsyncTask = new AsyncTask();
yourAsyncTask.setCallBack(this);
yourAsyncTask.excecute();
}
#Override
public void updateValue(int value){
Log.e(TAG,"Value : " + value);
}
}
EDIT 1 :
public class AdsHttpRequest {
private static final String TAG = AdsHttpRequest.class.getSimpleName(); // log
private GetHttpTask mGetAsyncTask;
private static AdsHttpRequest mInstance;
private OnGetRequestListener mCallBack;
private static final String SUCCESS = "success";
private static final String SUCCES = "succes";
private static final String FAILED = "fail";
/**
* #return a singleton instance of {#link AdsHttpRequest}
*/
public static AdsHttpRequest getInstance() {
if (mInstance == null) {
synchronized (AdsHttpRequest.class) {
if (mInstance == null) {
mInstance = new AdsHttpRequest();
}
}
}
return mInstance;
}
/**
* Initialize the {#link AsyncTask}, set the callback, execute the task
*
* #param url
* url for the request
* #param callback
* {#link OnGetRequestListener} for feed back
*/
public void post(String url, OnGetRequestListener callback) {
mCallBack = callback;
if (mGetAsyncTask == null) {
mGetAsyncTask = new GetHttpTask();
} else {
cancelGetTask();
mGetAsyncTask = new GetHttpTask();
}
mGetAsyncTask.execute(url);
}
/**
* cancel the {#link AsyncTask} if it's still alive <br>
* <b>see </b> {#link Status}
*/
public void cancelGetTask() {
if (mGetAsyncTask != null && mGetAsyncTask.getStatus().equals(Status.RUNNING)) {
mGetAsyncTask.cancel(true);
}
mGetAsyncTask = null;
}
private AdsHttpRequest() {
super();
}
/**
* Actually construct and launch the HTTP request
*
* #param url
* url of the request
* #return response of the server
*/
private String getResponseFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
Log.e(TAG, "", e);
}
return xml;
}
/**
* Manage the http request in background
*
* #param String
* url for the request
*/
private class GetHttpTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
if (params[0] != null) {
return getResponseFromUrl(params[0]); // return the response of the server
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if (result.contains(SUCCES) || result.contains(SUCCESS)) {
mCallBack.onGetRequestResult(SUCCESS);
} else {
mCallBack.onGetRequestResult(FAILED);
}
}
}
}
}
The way that I'm doing this consume more memory, time, threads? (I'm guessing)

Categories

Resources