I am working with Microsoft Azure Cloud Database, inserting data from Android Application.
i referred below mentioned link code,for insert and fetch data from azure using my android App. its Works fine.
Problem:
I have added two more columns in Azure database. I am not able to interact that columns using demo code.its little complicated for me.
Please help me,how to add few more columns in android code,Insert and Fetching data from cloud Database.
Link i referred
ToDoActivity.java
public class ToDoActivity extends Activity {
/**
* Mobile Service Client reference
*/
private MobileServiceClient mClient;
/**
* Mobile Service Table used to access data
*/
private MobileServiceTable<ToDoItem> mToDoTable;
//Offline Sync
/**
* Mobile Service Table used to access and Sync data
*/
//private MobileServiceSyncTable<ToDoItem> 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://newapk.azure-mobile.net/",
"****************************",
this).withFilter(new ProgressFilter());
// Get the Mobile Service Table instance to use
mToDoTable = mClient.getTable(ToDoItem.class);
// Offline Sync
//mToDoTable = mClient.getSyncTable("ToDoItem", ToDoItem.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 entity;
}
/**
* 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<ToDoItem> results = refreshItemsFromMobileServiceTable();
//Offline Sync
//final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.clear();
for (ToDoItem 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<ToDoItem> refreshItemsFromMobileServiceTable() throws ExecutionException, InterruptedException {
return mToDoTable.where().field("complete").
eq(val(false)).execute().get();
}
//Offline Sync
/**
* Refresh the list with the items in the Mobile Service Sync Table
*/
/*private List<ToDoItem> refreshItemsFromMobileServiceTableSyncTable() throws ExecutionException, InterruptedException {
//sync the data
sync().get();
Query query = QueryOperations.field("complete").
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(), "OfflineStore", null, 1);
Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
tableDefinition.put("id", ColumnDataType.String);
tableDefinition.put("text", ColumnDataType.String);
tableDefinition.put("complete", ColumnDataType.Boolean);
localStore.defineTable("ToDoItem", 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;
}
}
}
ToDoItemAdapter.java
public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
/**
* Adapter context
*/
Context mContext;
/**
* Adapter View layout
*/
int mLayoutResourceId;
public ToDoItemAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
/**
* Returns the view for a specific item on the list
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ToDoItem currentItem = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkToDoItem);
checkBox.setText(currentItem.getText());
checkBox.setChecked(false);
checkBox.setEnabled(true);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (checkBox.isChecked()) {
checkBox.setEnabled(false);
if (mContext instanceof ToDoActivity) {
ToDoActivity activity = (ToDoActivity) mContext;
activity.checkItem(currentItem);
}
}
}
});
return row;
}
}
ToDoItem.java
public class ToDoItem {
/**
* Item text
*/
#com.google.gson.annotations.SerializedName("text")
private String mText;
/**
* Item Id
*/
#com.google.gson.annotations.SerializedName("id")
private String mId;
/**
* Indicates if the item is completed
*/
#com.google.gson.annotations.SerializedName("complete")
private boolean mComplete;
/**
* ToDoItem constructor
*/
public ToDoItem() {
}
#Override
public String toString() {
return getText();
}
/**
* Initializes a new ToDoItem
*
* #param text
* The item text
* #param id
* The item id
*/
public ToDoItem(String text, String id) {
this.setText(text);
this.setId(id);
}
/**
* Returns the item text
*/
public String getText() {
return mText;
}
/**
* Sets the item text
*
* #param text
* text to set
*/
public final void setText(String text) {
mText = text;
}
/**
* Returns the item id
*/
public String getId() {
return mId;
}
/**
* Sets the item id
*
* #param id
* id to set
*/
public final void setId(String id) {
mId = id;
}
/**
* Indicates if the item is marked as completed
*/
public boolean isComplete() {
return mComplete;
}
/**
* Marks the item as completed or incompleted
*/
public void setComplete(boolean complete) {
mComplete = complete;
}
#Override
public boolean equals(Object o) {
return o instanceof ToDoItem && ((ToDoItem) o).mId == mId;
}
}
There are a documents https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/ that clearly explained how to use the android clinet library to interact with Azure Database for various operations.
I think you can refer to these sample in the document to write own code to implement your needs.
Any other concern, please feel free to let me know.
You have to make changes in your ToDoItem.java
It is the class which corresponds to the table in database.
whenever you make changes to the table in azure.
In ur case, when u are adding new columns to table in azure, say newcol1 and newcol2, You have to add
#com.google.gson.annotations.SerializedName("newcol1")
private boolean newColumnOne;
to your ToDoItem.java file. Only then u could have access to new columns in ToDoActivity.java
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);
item.setNewColumnOne("dataabc");
item.setNewColumnTwo("dataxyz");
// 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 3rd");
}
return null;
}
};
runAsyncTask(task);
mTextNewToDo.setText("");
}
just add data through setNewColumnOne(); as i did.
rest of the code should be same.
P.S. dont forget to create getter setter and constructor for TodoItem.Java
Related
I want to display this textview "txtCalculate" which comes from the class CustomerMapActivity which is displayed in the activity_map_customer layout in another layout which is activity_bon_de_commande, of the class BonDeCommande.
the problem is I don't know how to do it
I'm new to java programming
thank you
public void readValues(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query lastQuery = ref.child("ride_info").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
double value0_float = ds.child("pickup").child("lat").getValue(Double.class);
double value1_float = ds.child("pickup").child("lng").getValue(Double.class);
double value2_float = ds.child("destination").child("lat").getValue(Double.class);
double value3_float = ds.child("destination").child("lng").getValue(Double.class);
String pickupLat = String.valueOf(value0_float);
String pickupLng = String.valueOf(value1_float);
String destiLat = String.valueOf(value2_float);
String destiLng = String.valueOf(value3_float);
String requestUrl=null;
try {
requestUrl = "https://maps.googleapis.com/maps/api/directions/json?"+
"mode=driving&"
+"transit_routing_preference=less_driving&"
+"origin="+pickupLat+","+pickupLng+"&"
+"destination="+destiLat+","+destiLng+"&"
+"key="+getResources().getString(R.string.google_maps_key);
Log.e("LINK",requestUrl);
mService.getPath(requestUrl).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObject = legs.getJSONObject(0);
//Get distance
JSONObject distance = legsObject.getJSONObject("distance");
String distance_text = distance.getString("text");
//use regex to extract double from string
//This regex will remove all text not digit
Double distance_value= Double.parseDouble(distance_text.replaceAll("[^0-9\\\\.]+",""));
//Get Time
JSONObject time = legsObject.getJSONObject("duration");
String time_text = time.getString("text");
Integer time_value = Integer.parseInt(time_text.replaceAll("\\D+",""));
String final_calculate = String.format("%.2f €",
TypeObject.getPrice(distance_value,time_value));
HERE -----> txtCalculate.setText(final_calculate);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mCurrentRide.cancelRide();
endRide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
mCurrentRide.cancelRide();
endRide();
}
});
}
screenshot of my screen
You need to Create an Interface with an update method, declare in your Activity and after, pass as parameter to your handler object that gets the data.
Don't forget If you're getting the data in a different Thread, you need to update your views always in an UI Thread or in the Main Thread.
Here Follow some example code:
Your Activity or Fragment
public class MainActivity extends AppCompatActivity
implements UpdateViewCallback { // implement the interface here
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = findViewById(R.id.textView);
// Pass the interface in your Object that makes the async work
final AsyncWork asyncWork = new AsyncWork(this);
// Running
Thread thread = new Thread(asyncWork);
thread.start();
}
/**
* UpdateViewCallback
* #param result
*/
#Override
public void updateView(final String result) {
// Always update View on MainThread or an UI Thread, or else issues will start to happening
this.runOnUiThread(new Runnable() {
public void run() {
// Check if View is null since you're updating in a thread async
if (textView != null) {
textView.setText(result);
}
}
});
}
}
Your Interface:
public interface UpdateViewCallback {
void updateView(String result);
}
Your Object to handle the Async Work:
public class AsyncWork implements Runnable {
private UpdateViewCallback updateViewCallback;
public AsyncWork(UpdateViewCallback updateViewCallback) {
this.updateViewCallback = updateViewCallback;
}
/**
* Async Work here
*/
#Override
public void run() {
// Do some Work and after update using the interface you passed in the constructor
updateViewCallback.updateView("This is a test");
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm doing some project and I'm stuck ... I'm doing something wrong, probably with AsyncTask and I have no idea what to fix and how .... there is code I have right now.
ReviewData.class
public class ReviewData implements Parcelable {
private String mAuthor, mContent;
public ReviewData(String author, String content) {
this.mAuthor = author;
this.mContent = content;
}
private ReviewData(Parcel in) {
mAuthor = in.readString();
mContent = in.readString();
}
public static final Creator<ReviewData> CREATOR = new Creator<ReviewData>() {
#Override
public ReviewData createFromParcel(Parcel in) {
return new ReviewData(in);
}
#Override
public ReviewData[] newArray(int size) {
return new ReviewData[size];
}
};
//Getter method for review author
public String getAuthor() {
return mAuthor;
}
//Setter method for review author
public void setAuthor(String author) {
this.mAuthor = author;
}
//Getter method for review content
public String getContent() {
return mContent;
}
//Setter method for review content
public void setContent(String content) {
this.mContent = content;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mAuthor);
dest.writeString(mContent);
}
}
ReviewAdapter.class
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ReviewViewHolder> {
private ArrayList<ReviewData> mReviewList;
private Context mContext;
public ReviewAdapter(Context context, ArrayList<ReviewData> reviewList) {
this.mContext = context;
this.mReviewList = reviewList;
}
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
View view = LayoutInflater.from(mContext).inflate(R.layout.review_item_list,
parent, false);
view.setFocusable(true);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(final ReviewViewHolder holder, int position) {
if(mReviewList != null) {
ReviewData reviewData = mReviewList.get(position);
holder.reviewAuthor.setText(reviewData.getAuthor());
holder.reviewContent.setText(reviewData.getContent());
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
if(mReviewList == null) {
return 0;
} else {
return mReviewList.size();
}
}
public void setReviewList(ArrayList<ReviewData> reviewList) {
if(reviewList != null) {
mReviewList = new ArrayList<>(reviewList);
}
notifyDataSetChanged();
}
public class ReviewViewHolder extends RecyclerView.ViewHolder {
TextView reviewAuthor;
TextView reviewContent;
public ReviewViewHolder(View itemView) {
super(itemView);
reviewAuthor = itemView.findViewById(R.id.review_author);
reviewContent = itemView.findViewById(R.id.review_content);
}
}
}
NetworkUtils.class (but only code for Review url builder, for other thing works perfectly). PS. this parse is written as API documentation said ... it should be someurl/movie/{id}/reviews
//URL builder for reviews
public static URL buildReviewUrl(String id) {
Uri builtUri = Uri.parse(BASE_MOVIE_URL + id + REVIEW).buildUpon()
.appendQueryParameter(QUERY_API_KEY, API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
JsonData. class (also, only for Reviews, for other works perfectly...)
//JSON for Review
public static ArrayList<ReviewData> getReviewFromJson(String json) throws JSONException {
ArrayList<ReviewData> listOfReviews = new ArrayList<>();
try {
JSONObject reviews = new JSONObject(json);
JSONArray reviewsArray = reviews.getJSONArray(QUERY_RESULTS);
for(int i = 0; i < reviewsArray.length(); i++) {
JSONObject jsonReview = reviewsArray.getJSONObject(i);
String author = jsonReview.optString(REVIEW_AUTHOR);
String content = jsonReview.optString(REVIEW_CONTENT);
ReviewData reviewData = new ReviewData(author, content);
listOfReviews.add(reviewData);
}
} catch(JSONException e) {
e.printStackTrace();
Log.e("ReviewJson", "JSON Review Error");
}
return listOfReviews;
}
ReviewAsyncTask.class
public class ReviewAsyncTask extends AsyncTask<String, Void, ArrayList<ReviewData>> {
private ReviewData mReviewData;
public interface ReviewResponse {
void finished(ArrayList<ReviewData> output);
}
private ReviewResponse reviewResponse = null;
public ReviewAsyncTask(ReviewResponse reviewResponse) {
this.reviewResponse = reviewResponse;
}
#Override
protected ArrayList<ReviewData> doInBackground(String... strings) {
String rawData = "";
ArrayList<ReviewData> reviewList = new ArrayList<>();
try {
rawData = NetworkUtils.getResponseFromHttpRequest(NetworkUtils
.buildReviewUrl(String.valueOf(mReviewData)));
reviewList = JsonData.getReviewFromJson(rawData);
} catch (IOException e) {
e.printStackTrace();
Log.e("ReviewAsyncTask", "Error in ReviewAsyncTask");
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONAsync", "JSON problem");
}
return reviewList;
}
#Override
protected void onPostExecute(ArrayList<ReviewData> reviewData) {
reviewResponse.finished(reviewData);
}
}
and MovieDetails activity (everything works fine except from the comment recycle review to next comment.
public class MovieDetails extends AppCompatActivity implements ReviewAsyncTask.ReviewResponse {
private final static String BASE_URL = "http://image.tmdb.org/t/p/";
private final static String SIZE = "w185/";
private ArrayList<ReviewData> mReviewList;
private ReviewAdapter mReviewAdapter;
#BindView(R.id.poster_detail)
ImageView mMoviePoster;
#BindView(R.id.title_detail)
TextView mMovieTitle;
#BindView(R.id.release_date)
TextView mReleaseDate;
#BindView(R.id.average_vote)
TextView mAverageVote;
#BindView(R.id.synopsis)
TextView mSynopsis;
#BindView(R.id.review_recycler)
RecyclerView mReviewRecycle;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
ButterKnife.bind(this);
displayMovieDetail();
//Review RecycleView
mReviewList = new ArrayList<>();
mReviewAdapter = new ReviewAdapter(this, mReviewList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mReviewRecycle.setLayoutManager(layoutManager);
mReviewRecycle.setHasFixedSize(true);
mReviewRecycle.setAdapter(mReviewAdapter);
}
#Override
public void finished(ArrayList<ReviewData> output) {
ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this);
reviewAsyncTask.execute();
}
/* Method for displaying the info about movies in activity details
* #param mMoviePoster sets the movie poster
* #param mMovieTitle sets original title of the movie
* #param mReleaseDate sets release date of the movie
* #param mAverageVote sets average rating grade of the movie
* #param mSynopsis sets plot of the movie */
private void displayMovieDetail() {
int idMovie = (Integer) getIntent().getExtras().get(getString(R.string.movie_id));
List<MovieData> movieList;
movieList = getIntent().getParcelableArrayListExtra(getString(R.string.movie_lsit));
MovieData movieData = movieList.get(idMovie);
Picasso.with(mContext).load(BASE_URL + SIZE +
movieData.getPoster()).into(mMoviePoster);
mMovieTitle.setText(movieData.getTitle());
mReleaseDate.setText(movieData.getReleaseDate());
mAverageVote.setText(Double.toString(movieData.getRating()));
mSynopsis.setText(movieData.getSynopsis());
}
}
P.S. I would share github link but I should give you my personal API key. :(
You need to start the AsyncTask in onCreate() (like you did before) and in finished() you take the results and add them to the Adapter's data list.
Finally, don't forget to call notifyDatasetChanged().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
// skipping some lines of code here...
mReviewRecycle.setAdapter(mReviewAdapter);
ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this);
reviewAsyncTask.execute();
}
#Override
public void finished(ArrayList<ReviewData> output) {
mReviewList.addAll(output);
mReviewAdapter.notifyDatasetChanged();
}
(Please note that I skipped null checks and error handling for brevity's sake)
In MovieDetails onCreate retrieve current movie ID like you do in displayMovieDetail.
Send that ID to ReviewAsyncTask (you'll need to modify constructor of ReviewAsyncTask)
Retrieve id in ReviewAsyncTask, save it as member variable, and then in doInBackground method send that id to buildReviewUrl as an argument.
I'm trying to pass data from a json file to a viewpager. I have followed most of the advice previously given to me here but it returns blank, without even crashing.
The four files involved in this:
1. The main fragment:
public class FashionFeed extends Fragment {
ViewPager viewPager;
PagerAdapter adapter;
ThePagerAdapter newdapter;
public static final String URL =
"http://celebirious.com/bey/data/space.json";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_whats_hot, null);
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPager.setClipToPadding(false);
viewPager.setPadding(4, 0, 4, 0);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20 * 2, getResources().getDisplayMetrics());
viewPager.setPageMargin(-margin);
new SimpleTask().execute(URL);
return v;
}
private class SimpleTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// Create Show ProgressBar
}
protected String doInBackground(String... urls) {
String result = "";
try {
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader
(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return result;
}
protected void onPostExecute(String jsonString) {
showData(jsonString);
}
}
private void showData(String jsonString) {
Gson gson = new Gson();
Style style = gson.fromJson(jsonString, Style.class);
List<Space> space = style.getSpace();
newdapter = new ThePagerAdapter(getActivity(), space);
viewPager.setAdapter(newdapter);
}
}
The Adapter extending the Pager:
public class ThePagerAdapter extends PagerAdapter {
List<Space> list;
LayoutInflater inflater;
Context context;
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
public ThePagerAdapter(Context context,List<Space> list) {
this.list = list;
this.context = context; // red as well
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.styledeets, container,
false);
// Locate the TextViews in viewpager_item.xml
txtrank = (TextView) itemView.findViewById(R.id.date);
txtcountry = (TextView) itemView.findViewById(R.id.where);
txtpopulation = (TextView) itemView.findViewById(R.id.info);
// Capture position and set to the TextViews
txtrank.setText(list.get(position).getName());
txtcountry.setText(list.get(position).getDates());
txtpopulation.setText(list.get(position).getInfo());
String url = (list.get(position).getAvatarUrl());
imgflag = (ImageView) itemView.findViewById(R.id.photo);
Picasso.with(context)
.load(url)
.placeholder(R.mipmap.ic_launcher)
.error(R.drawable.ic_launcher_gmail)
.fit()
.tag(context)
.into(imgflag);
// Locate the ImageView in viewpager_item.xml
// Capture position and set to the ImageView
//imgflag.setImageResource(flag[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Gson data retreived from jsonschema2pojo.org:
Space.java
public class Space {
#Expose
private String name;
#Expose
private String dates;
#Expose
private String type;
#Expose
private String social;
#Expose
private String info;
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The dates
*/
public String getDates() {
return dates;
}
/**
*
* #param dates
* The dates
*/
public void setDates(String dates) {
this.dates = dates;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* #return
* The social
*/
public String getSocial() {
return social;
}
/**
*
* #param social
* The social
*/
public void setSocial(String social) {
this.social = social;
}
/**
*
* #return
* The info
*/
public String getInfo() {
return info;
}
/**
*
* #param info
* The info
*/
public void setInfo(String info) {
this.info = info;
}
/**
*
* #return
* The avatarUrl
*/
public String getAvatarUrl() {
return avatarUrl;
}
/**
*
* #param avatarUrl
* The avatar_url
*/
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
Lastly, Style.java
public class Style {
#Expose
private List<Space> space = new ArrayList<Space>();
/**
*
* #return
* The space
*/
public List<Space> getSpace() {
return space;
}
/**
*
* #param space
* The space
*/
public void setSpace(List<Space> space) {
this.space = space;
}
}
All the xml data is properly linked 'cause this all works when it is retrieving data locally. What could be wrong?
I figured this out !!!!! How silly of me.
Was
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
should have been:
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
I'm trying to mock the GPS location in my app but as soon as I set mocked location, any app using the google play services is unable to get the location of the device, whether it's the real one or the mocked one.
For instance, if I open Google Map and try to go to my location, i'll get the message
waiting for the location
and nothing will happen. That's the same in my app, the location is never found
my code is the following:
public class MockLocationService {
protected Context context;
// Define a LocationClient object
public LocationClient mLocationClient;
// provider of fake locations
private static final String PROVIDER = "flp";
// TAG for the logs
protected static final String TAG = "MockLocationService";
// intens for states
public static final String MOCK_LOCATION_SERVICE_CONNECTED = "CONNECTED";
public static final String MOCK_LOCATION_SERVICE_DECONNECTED = "DECONNECTED";
public static final String MOCK_LOCATION_SERVICE_FAILED = "FAILED";
public static final String MOCK_LOCATION_SERVICE_SETTING_NOT_ENABLED = "SETTING_NOT_ENABLED";
// current mockLocation
protected static Location currentMockLocation;
public MockLocationService(Context context) {
this.context = context;
// connect to the Google play services
mLocationClient = new LocationClient(context, connectionCallbacks,
onConnectionFailedListener);
}
/**
* Connect to the API to enable mocking the location
*/
public void connect() {
// Connect to Location Services
// ONLY WHEN CALLBACK IS CALLED, ACT
mLocationClient.connect();
}
/**
* Disconnect from the API, stops mocking the location
*/
public void disconnect() {
// terminate aTask
aTask.cancel(true);
currentMockLocation=null;
// disconnect
mLocationClient.disconnect();
}
/**
* Sets the location from a LocationMessage object as the device current
* location
*
* #param location
*/
public void setLocation(LocationMessage location) {
if (location.getLat() == null || location.getLng() == null
|| location.getAccuracy() == null)
return;
Location newLocation = new Location(PROVIDER);
newLocation.setLatitude(location.getLat());
newLocation.setLongitude(location.getLng());
newLocation.setAccuracy(1);
newLocation.setTime(System.currentTimeMillis());
newLocation.setBearing(0F);
newLocation.setAltitude(0F);
// set it as a mocked location
this.setMockLocation(newLocation);
// Create a new Location
Log.d(TAG,
"New mocked location: lat: " + location.getLat() + " - lng: "
+ location.getLng() + " - accuracy: "
+ location.getAccuracy());
}
/**
* Sets a Location object as the location for the device
*
* #param mockLocation
* the mocked Location object
*/
protected void setMockLocation(Location mockLocation) {
if (!mLocationClient.isConnected())
return;
currentMockLocation = mockLocation;
if (currentMockLocation==null) {
aTask.execute((Void) null);
}
}
// asynchronously send the mock location every second (for GPS)
final RestAsyncTask<Boolean[]> aTask = new RestAsyncTask<Boolean[]>() {
// executes on background thread
#Override
protected Boolean[] doInBackground(Void... lists) {
// set mock location
do {
mLocationClient.setMockLocation(currentMockLocation);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
#Override
protected void onPostExecute(Boolean[] result) {
return;
}
};
/**
* When connect/unconnect from the location client
*/
protected ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks() {
#Override
public void onDisconnected() {
sendIntent(MOCK_LOCATION_SERVICE_DECONNECTED);
}
#Override
public void onConnected(Bundle arg0) {
sendIntent(MOCK_LOCATION_SERVICE_CONNECTED);
// When the location client is connected, set mock mode
try {
mLocationClient.setMockMode(true);
} catch (Exception e) {
sendIntent(MOCK_LOCATION_SERVICE_SETTING_NOT_ENABLED);
}
}
};
/**
* When connection failed to the location client
*/
protected OnConnectionFailedListener onConnectionFailedListener = new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
sendIntent(MOCK_LOCATION_SERVICE_FAILED);
}
};
/**
* Send an intent with the correct type
*
* #param action
* : the action parameter of the intent
*/
protected static void sendIntent(String action) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(action);
LocalBroadcastManager.getInstance(PEApplication.getInstance())
.sendBroadcast(broadcastIntent);
}
}
am I missing something?
thanks!
I'm getting a json exception when I try to run my code.
The problem happens on the onclick listener. I'm trying to have the application go to the article of the rss feed on click
Here is the main activity
public class Blocku extends ListActivity {
private RssListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<JSONObject> jobs = new ArrayList<JSONObject>();
try {
jobs = BlockuReader.getLatestRssFeed();
} catch (Exception e) {
Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
}
adapter = new RssListAdapter(this,jobs);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String link = null;
try {
String url = Article.getUrl().toString();
link = adapter.getItem(position).getString(url).toString();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(link));
startActivity(i);
} catch (JSONException e) {
Context context = getApplicationContext();
CharSequence text = "error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
e.printStackTrace();
}
}
}
here is the adapter:
public class RssListAdapter extends ArrayAdapter<JSONObject> {
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
super(activity, 0, imageAndTexts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = inflater.inflate(R.layout.image_text_layout, null);
JSONObject jsonImageText = getItem(position);
//////////////////////////////////////////////////////////////////////////////////////////////////////
//The next section we update at runtime the text - as provided by the JSON from our REST call
////////////////////////////////////////////////////////////////////////////////////////////////////
TextView textView = (TextView) rowView.findViewById(R.id.job_text);
try {
Spanned text = (Spanned)jsonImageText.get("text");
textView.setText(text);
} catch (JSONException e) {
textView.setText("JSON Exception");
}
return rowView;
}
}
and the article class
public class Article {
private long articleId;
private long feedId;
private String title;
private String description;
private String pubDate;
private static URL url;
private String encodedContent;
private static String link;
/**
* #return the articleId
*/
public long getArticleId() {
return articleId;
}
/**
* #param articleId the articleId to set
*/
public void setArticleId(long articleId) {
this.articleId = articleId;
}
/**
* #return the feedId
*/
public long getFeedId() {
return feedId;
}
/**
* #param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the url
*/
public static URL getUrl() {
return url;
}
/**
* #param url the url to set
*/
public void setUrl(URL url) {
Article.url = url;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* #return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* #param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* #return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
}
JSONException is usually thrown when there are issues with parsing. Check how you are parsing the JSON. this says that you are trying to get a value for a key named "then it lists the site i want"