I do not know what to call this error. My app uses a self written shared preferences class. After a few times of running my app, nothing can be retrieved from my remote server. I'll post my shared preferences and one my my async tasks. There is no error within the logcat when the app does not retrieve anything.
Shared Preferences class:
public class SharedPreferences{
static final String PREF_USER_NAME = "username";
static final String PREF_USER_ID = "userid";
static android.content.SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static void setUserId(Context ctx, String userId)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_ID, userId);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
public static String getUserId(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_ID, "");
}
public static void clearUserName(Context ctx)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.clear(); //clear all stored data
editor.commit();
}
}
Item retrieval async task:
public class GetEventsAsyncTask extends AsyncTask<String, Integer, Boolean>{
ProgressDialog progressDialog;
MainActivity activityMain;
List<Event> eventList = new ArrayList<Event>();
MyDbAdapter db;
public GetEventsAsyncTask(MainActivity parent)
{
activityMain = parent;
}
#Override
protected void onPreExecute() {
// progressDialog = null;
//
// if (progressDialog == null)
// {
// progressDialog = new ProgressDialog(activityMain);
// progressDialog.setMessage("download events, please wait...");
// progressDialog.show();
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// }
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean error = false;
try {
error = postData(params[0]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
protected void onPostExecute(Boolean error){
/* if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
} */
if(error==true)
{
Log.i("GetEvents", "Error at get events");
activityMain.errorOccured();
}
else
{
Log.i("onPostExecute:eventlist.count",String.valueOf(eventList.size()));
MainActivity.myDB.removeAllEvents();
for(int i=0;i<eventList.size();i++)
{
MainActivity.myDB.insertEventEntry(eventList.get(i));
}
activityMain.downloadEventsSuccess(eventList);
// progressDialog.dismiss();
}
}
protected void onProgressUpdate(Integer... progress){
}
public Boolean postData(String user_id) throws JSONException {
Boolean error = false;
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
try {
Log.i("GetEvents", user_id);
HttpGet httpget = new HttpGet(Constants.HOST_NAME+"/"+Constants.SERVICE_NAME+"/api/Event?userId=" + user_id);
BufferedReader reader;
StringBuffer sb;
String line = "";
String NL="";
String json;
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode()==200)
{
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
sb = new StringBuffer("");
line = "";
NL = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
sb.append(line + NL);
}
reader.close();
json = sb.toString();
Log.i("event json",json);
try
{
JSONArray jsonArray = new JSONArray(json);
for (int i = 0, length = jsonArray.length(); i < length; i++)
{
JSONObject attribute = jsonArray.getJSONObject(i);
Log.i("EventsAsync", attribute.toString(i));
Event eventObj = new Event();
eventObj.setEvent_id(attribute.getString("event_id"));
eventObj.setEvent_title(attribute.getString("event_title"));
eventObj.setEvent_desc(attribute.getString("event_desc"));
eventObj.setStart_date(attribute.getString("start_date"));
eventObj.setEnd_date(attribute.getString("end_date"));
eventObj.setStart_time(attribute.getString("start_time"));
eventObj.setEnd_time(attribute.getString("end_time"));
eventObj.setLocation(attribute.getString("location"));
eventObj.setPicture_path(attribute.getString("picture_path"));
eventObj.setSmall_picture_path(attribute.getString("small_picture_path"));
eventList.add(eventObj);
// DatabaseUser.openWritable();
// DatabaseUser.insertEvent(eventObj);
eventObj = null;
}
}
catch (JSONException e)
{
e.printStackTrace();
error = true;
}
}
else
{
error = true;
}
}
catch (ClientProtocolException e)
{
// process execption
error = true;
}
catch (IOException e)
{
// process execption
error = true;
}
return error;
}
}
Most of the time, the app stops retrieving after 3 times from onStart to onDestroy.
Related
code which one should I change to throw button and instantly displays my listview without having to click a button
public class MainActivity extends AppCompatActivity {
Button btnLoadFeed; <<<<<------------- Which should I remove associated with this code?
TextView textViewFeedUrl;
ListView listViewFeed;
List<FeedItem> listFeedItems;
ListAdapter adapterFeed;
String myFeed = "http://temfilm.blogspot.co.id/feeds/posts/default?alt=json";
//String myFeed = "http://arduino-er.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://helloraspberrypi.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://photo-er.blogspot.com/feeds/posts/default?alt=json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadFeed = (Button)findViewById(R.id.loadfeed);
textViewFeedUrl = (TextView)findViewById(R.id.feedurl);
setContentView(R.layout.layout_feed);
listViewFeed = (ListView)findViewById(R.id.listviewfeed);
listFeedItems = new ArrayList<>();
adapterFeed = new ArrayAdapter<FeedItem>(
this, android.R.layout.simple_list_item_1, listFeedItems);
listViewFeed.setAdapter(adapterFeed);
btnLoadFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewFeedUrl.setText(myFeed);
new JsonTask(listFeedItems, listViewFeed).execute(myFeed);
}
});
}
/*
JsonTask:
AsyncTask to download and parse JSON Feed of blogspot in background
*/
private class JsonTask extends AsyncTask<String, FeedItem, String> {
List<FeedItem> jsonTaskList;
ListView jsonTaskListView;
public JsonTask(List<FeedItem> targetList, ListView targetListView) {
super();
jsonTaskList = targetList;
jsonTaskListView = targetListView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonTaskList.clear();
jsonTaskListView.invalidateViews();
}
#Override
protected String doInBackground(String... params) {
try {
final String queryResult = sendQuery(params[0]);
parseQueryResult(queryResult);
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
FeedItem newItem = values[0];
jsonTaskList.add(newItem);
jsonTaskListView.invalidateViews();
}
private String sendQuery(String query) throws IOException {
String queryReturn = "";
URL queryURL = new URL(query);
HttpURLConnection httpURLConnection = (HttpURLConnection)queryURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader =
new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader, 8192);
String line = null;
while((line = bufferedReader.readLine()) != null){
queryReturn += line;
}
bufferedReader.close();
}
return queryReturn;
}
private void parseQueryResult(String json) throws JSONException {
JSONObject jsonObject = new JSONObject(json);
final JSONObject jsonObject_feed = jsonObject.getJSONObject("feed");
final JSONArray jsonArray_entry = jsonObject_feed.getJSONArray("entry");
runOnUiThread(new Runnable() {
#Override
public void run() {
if(jsonArray_entry == null){
Toast.makeText(MainActivity.this,
"jsonArray_entry == null",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,
String.valueOf(jsonArray_entry.length()),
Toast.LENGTH_LONG).show();
for(int i=0; i<jsonArray_entry.length(); i++){
try {
JSONObject thisEntry = (JSONObject) jsonArray_entry.get(i);
JSONObject thisEntryTitle = thisEntry.getJSONObject("title");
String thisEntryTitleString = thisEntryTitle.getString("$t");
JSONArray jsonArray_EntryLink = thisEntry.getJSONArray("link");
//search for the link element with rel="alternate"
//I assume it's one and only one element with rel="alternate",
//and its href hold the link to the page
for(int j=0; j<jsonArray_EntryLink.length(); j++){
JSONObject thisLink = (JSONObject) jsonArray_EntryLink.get(j);
try{
String thisLinkRel = thisLink.getString("rel");
if(thisLinkRel.equals("alternate")){
try{
String thisLinkHref = thisLink.getString("href");
FeedItem thisElement = new FeedItem(
thisEntryTitleString.toString(),
thisLinkHref);
publishProgress(thisElement);
break;
}catch (JSONException e){
//no such mapping exists
}
}
}catch (JSONException e){
//no such mapping exists
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
}
}
}
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
I have an Async task that loads information from the server and displays data on the UI. Suddenly the async task downloads the data and formats the JSON data fine but it would freeze the UI completely.
Here is the base download class
public class GetRawData {
private static String LOG_TAG = GetRawData.class.getSimpleName();
private String mRawURL;
private List<NameValuePair> mRawParams = null;
private String mRawData;
private DownloadStatus mDownloadStatus;
public GetRawData(String mRawURL) {
this.mRawURL = mRawURL;
this.mRawParams = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public String getRawData() {
return mRawData;
}
public void setRawURL(String mRawURL) {
this.mRawURL = mRawURL;
}
public List<NameValuePair> getRawParams() {
return mRawParams;
}
public void setRawParams(List<NameValuePair> mParams) {
this.mRawParams = mParams;
}
public DownloadStatus getDownloadStatus() {
return mDownloadStatus;
}
public void reset() {
this.mRawURL = null;
this.mRawData = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public void execute() {
this.mDownloadStatus = DownloadStatus.PROCESSING;
DownloadRawData mDownloadRawData = new DownloadRawData();
mDownloadRawData.execute(mRawURL);
}
public class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Create URL and Reader instances.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//If no parameter has been provided, return null.
if (params == null)
return null;
try {
// Get URL entered by the user.
URL mURL = new URL(params[0]);
urlConnection = (HttpURLConnection) mURL.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
//urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.connect();
// validate and add parameters if available.
if (mRawParams != null && mRawParams.size()>0){
JSONObject jsonParam = new JSONObject();
for (NameValuePair pair : mRawParams) {
jsonParam.put(pair.getName().toString(), pair.getValue().toString());
}
String jsonparams = jsonParam.toString();
// Send POST output.
DataOutputStream printout;
printout = new DataOutputStream(urlConnection.getOutputStream());
printout.writeBytes(jsonparams);
printout.flush();
printout.close();
}
int HttpResult =urlConnection.getResponseCode();
StringBuffer buffer = new StringBuffer();
if(HttpResult ==HttpURLConnection.HTTP_OK){
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(""+buffer.toString());
}else{
InputStream errorStream = urlConnection.getErrorStream();
if (errorStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(errorStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(urlConnection.getResponseMessage());
}
return buffer.toString();
} catch (IOException e) {
Log.d("IOException", e.toString());
return null;
} catch (JSONException j) {
Log.d("JSONException", j.toString());
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.d("IOException", "unable to close the reader");
}
}
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mRawData = result;
//Log.d("onPostExecute", result);
if (mRawData == null) {
if (mRawURL == null) {
mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
} else {
mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
}
} else {
mDownloadStatus = DownloadStatus.PROCESSED;
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
enum DownloadStatus {
IDLE,
PROCESSING,
NOT_INITIALIZED,
FAILED_OR_EMPTY,
PROCESSED
}
Here is the specific data formatting class the extends above class
public class GetJobCardJsonData extends GetRawData {
private static String LOG_TAG = GetAuthenticationJsonData.class.getSimpleName();
private static String JOBCARD_SERVICE_URL = "http://www.appservice.com/appservice/jobcardinfoservice.asmx/GetJobCardInfo";
private List<JobCard> mJobCardList;
private CarcalDownloadListener mListener;
public GetJobCardJsonData(String CurrentDate, int DealershipID) {
super(null);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("JobCardDate", CurrentDate));
mParams.add(new BasicNameValuePair("DealershipID", String.valueOf(DealershipID)));
this.setRawParams(mParams);
}
public List<JobCard> getJobCardList() {
return mJobCardList;
}
public void getjobcards() {
super.setRawURL(JOBCARD_SERVICE_URL);
DownloadJobCardJsonData mDownloadJobCardJsonData = new DownloadJobCardJsonData();
mDownloadJobCardJsonData.execute(JOBCARD_SERVICE_URL);
}
public void setOnCarcalDownloadListener(CarcalDownloadListener onCarcalDownloadListener) {
this.mListener = onCarcalDownloadListener;
}
private void processResult() {
if (getDownloadStatus() != DownloadStatus.PROCESSED) {
Log.e(LOG_TAG, "Error Downloading the raw file.");
return;
}
if (mJobCardList == null){
mJobCardList = new ArrayList<JobCard>();
}
final String JOBCARD_JOBCARDID = "JobCardID";
final String JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME = "StockNumberWithDeliveryTime";
final String JOBCARD_CUSTOMERNAME = "CustomerName";
final String JOBCARD_MODELNUMBER = "ModelNumber";
final String JOBCARD_COLOR = "Color";
final String JOBCARD_SALEEXECUTIVE = "SaleExecutive";
final String JOBCARD_ORDERSTATUS = "OrderStatus";
final String JOBCARD_SHOWROOMSTATUS = "ShowRoomStatus";
try {
JSONArray jsonArray = new JSONArray(getRawData());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobcarditem = jsonArray.optJSONObject(i);
Long JOBCARDID = jobcarditem.getLong(JOBCARD_JOBCARDID);
String STOCKWITHDELIVERY = jobcarditem.getString(JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME);
String CUSTOMERNAME = jobcarditem.getString(JOBCARD_CUSTOMERNAME);
String MODELNUMBER = jobcarditem.getString(JOBCARD_MODELNUMBER);
String COLOR = jobcarditem.getString(JOBCARD_COLOR);
String SALEEXECUTIVE = jobcarditem.getString(JOBCARD_SALEEXECUTIVE);
int ORDERSTATUS = jobcarditem.getInt(JOBCARD_ORDERSTATUS);
int SHOWROOMSTATUS = jobcarditem.getInt(JOBCARD_SHOWROOMSTATUS);
JobCard mJobCard = new JobCard(JOBCARDID, STOCKWITHDELIVERY, CUSTOMERNAME, MODELNUMBER, COLOR, SALEEXECUTIVE, ORDERSTATUS, SHOWROOMSTATUS);
mJobCardList.add(mJobCard);
}
} catch (JSONException jsone) {
jsone.printStackTrace();
Log.e(LOG_TAG, "Error processing json data.");
}
}
public class DownloadJobCardJsonData extends DownloadRawData {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
processResult();
mListener.OnDownloadCompleted();
}
}
}
Here is the code that is called on the activity
private JobCardRecyclerViewAdapter mJobCardRecyclerViewAdapter;
private GetJobCardJsonData mGetJobCardJsonData;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_card_calender);
activateToolbarWithHomeEnabled();
String formattedDate="";
if (session.getCurrentDate() == ""){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = df.format(c.getTime());
currentDateTextView.setText(formattedDate);
}else {
formattedDate = session.getCurrentDate();
currentDateTextView.setText(formattedDate);
}
// Fetch data for current date.
mGetJobCardJsonData = new GetJobCardJsonData(formattedDate, session.getDealershipID());
mGetJobCardJsonData.getjobcards();
mGetJobCardJsonData.setOnCarcalDownloadListener(new CarcalDownloadListener() {
#Override
public void OnDownloadCompleted() {
List<JobCard> mJobCards = mGetJobCardJsonData.getJobCardList();
mJobCardRecyclerViewAdapter = new JobCardRecyclerViewAdapter(mJobCards, JobCardCalenderActivity.this);
mRecyclerView.setAdapter(mJobCardRecyclerViewAdapter);
}
});
}
Can anyone help on what i am doing wrong that is freezing the UI. It was working fine before and has started to freeze the UI suddenly.
I was able to fix the issue, the problem was not with Async task but with the layout. I accidently wrapped the recycler view with scroll view. which was causing the UI to freeze. Looks weird that a scroll view caused the whole UI thread to freeze. but here is my solution
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
</ScrollView>
Changed it to
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
hope it will be helpful for others facing same problem.
Requesting access to token for second time doesn't work thats why we need to store the token for first time to use it in future reference.Thats what i am trying to do here in Twitter integration using SharedPreference while posting tweet.It works fine for the first time while posting tweet but shows popup in second time showing "You don't have access to appname.Please return to appname to continue signup process".
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
Below is my complete code for TwitterFragment.java
TwitterFragment.java
public class TwitterFragment extends ListFragment {
final static String ScreenName = "IBL_Official";
final static String LOG_TAG = "rnc";
private FragmentActivity myContext;
private ListFragment activity;
private ListView listView;
public static EditText tx1;
private ProgressBar mDialog;
private QuickReturnFrameLayout searchLayout;
Button login;
boolean requestTokenFirstTime = true;
twitter4j.Twitter twitter;
RequestToken requestToken = null;
//static RequestToken requestToken ;
twitter4j.auth.AccessToken accessToken;
String oauth_url,oauth_verifier,profile_url;
Dialog auth_dialog;
WebView web;
SharedPreferences pref;
ProgressDialog progress;
Bitmap bitmap;
#Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activity = this;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
downloadTweets();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.twit_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
tx1=(EditText)rootView.findViewById(R.id.postcomment);
mDialog = (ProgressBar) rootView.findViewById(R.id.progress_bar);
searchLayout = (QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout);
listView.setVerticalScrollBarEnabled(false);
((QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout)).attach(listView);
rootView.setVerticalScrollBarEnabled(false);
login = (Button)rootView.findViewById(R.id.postbutton);
pref = getActivity().getPreferences(0);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""), pref.getString("CONSUMER_SECRET", ""));
login.setOnClickListener(new LoginProcess());
return rootView;
}
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
public class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "AuSSA6AHeCv9gskRhGQjSymCO";
final static String CONSUMER_SECRET = "eyRoYBONVh45V185TBYbbb3i9BpWmmaiv4wLbBYXd7UcZGGaDw";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
public String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
#Override
public void onPreExecute() {
}
#Override
public void onPostExecute(String result) {
mDialog.setVisibility(View.GONE);
searchLayout.setVisibility(View.VISIBLE);
listView.setVisibility(View.VISIBLE);
Twitte twits = jsonToTwitter(result);
System.out.println(result);
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> link = new ArrayList<String>();
ArrayList<String> time = new ArrayList<String>();
String logoimage = "";
String name = "";
String officialname = "";
for (Tweet tweet : twits) {
String[] splitted = tweet.getText().split("http://");
Log.d("splitted", String.valueOf(splitted.length));
data.add(splitted[0]);
if (splitted.length > 1) {
link.add("http://" + splitted[1]);
} else {
link.add("");
}
logoimage = tweet.getUser().getProfileImageUrl();
name = tweet.getUser().getName();
officialname = "# " + tweet.getUser().getScreenName();
time.add(tweet.getDateCreated());
}
//
Bitmap image = null;
try {
URL url = new URL(logoimage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
image = getRoundedShape(image);
} catch (Exception e) {
Log.d("error in image", e.toString());
Log.d("image", logoimage);
}
try {
TwitterAdapter adapter = new TwitterAdapter(getActivity(), data, link, image, time, name, officialname);
listView.setAdapter(adapter);
} catch (Exception e) {
System.out.println("error");
}
}
public Twitte jsonToTwitter(String result) {
Twitte twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitte.class);
} catch (IllegalStateException ex) {
}
}
return twits;
}
public Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
}
}
return auth;
}
public String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
inputStream.close();
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
public String getTwitterStream(String screenName) {
String results = null;
try {
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
String combined = urlApiKey + ":" + urlApiSecret;
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW
);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null
);
return targetBitmap;
}
}
private class LoginProcess implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TokenGet().execute();
}}
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
#Override
protected void onPostExecute(String oauth_url) {
if(oauth_url != null){
Log.e("URL", oauth_url);
auth_dialog = new Dialog(getActivity());
auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(oauth_url);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("oauth_verifier") && authComplete == false){
authComplete = true;
Log.e("Url",url);
Uri uri = Uri.parse(url);
oauth_verifier = uri.getQueryParameter("oauth_verifier");
auth_dialog.dismiss();
new AccessTokenGet().execute();
}else if(url.contains("denied")){
auth_dialog.dismiss();
Toast.makeText(getActivity(), "Sorry !, Permission Denied", Toast.LENGTH_SHORT).show();
}
}
});
auth_dialog.show();
auth_dialog.setCancelable(true);
}else{
Toast.makeText(getActivity(), "Sorry !, Network Error or Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
private class AccessTokenGet extends AsyncTask<String, String, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data ...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
SharedPreferences.Editor edit = pref.edit();
edit.putString("ACCESS_TOKEN", accessToken.getToken());
edit.putString("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
User user = twitter.showUser(accessToken.getUserId());
profile_url = user.getOriginalProfileImageURL();
edit.putString("NAME", user.getName());
edit.putString("IMAGE_URL", user.getOriginalProfileImageURL());
edit.commit();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean response) {
if(response){
progress.hide();
// progress.dismiss();
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, profile);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
else{
auth_dialog.dismiss();
}
}
}
}
I think you may simply want to hang on to the oauth access token after the first attempt (or ask for it by calling twitter.getOAuthAccessToken() ) and reuse it for the second time.
I ran into a similar experience and I found that the twitter4j.Twitter twitter; instance already had an access token associated with this instance from my first attempt. So when I asked for the authentication url from the request token ( oauth_url = requestToken.getAuthorizationURL(); ) and opened it in a webpage I got a message similar to your problem description ( "You don't have access to Please return to to continue the signup process." ).
I think if you wanted to you could also start over by recreating the twitter4j.Twitter instance and the related instance variables (like the RequestToken ). However this would also require you to then do the whole authentication process again with would be repeating the same work you did on the first attempt.
I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}