While I was searching for how to fire my own activity for links in html parsed with Jsoup, I stumbled upon LinkEnabledTextView
In the demo, it was implemented for strings but in my case, I am fetching the text from the web and displaying it in a TextView.
In the accepted answer in this question, it was applied to listitem. I followed the instructions in both links but I am having
problems applying it to my scenario.
NewsDetails class
public class NewsDetails extends AppCompatActivity implements TextLinkClickListener{
TextView newsTitle;
LinkEnabledTextView newsContent;
private String news_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
showDialog();
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsAuthorDate = (TextView) findViewById(R.id.author_date);
newsContent = (LinkEnabledTextView) findViewById(R.id.dnews_content);
check = new LinkEnabledTextView(this, null);
check.setOnTextLinkListener(this);
check.gatherLinksForText(String.valueOf(newsContent));
check.setTextColor(Color.BLUE);
check.setLinkTextColor(Color.RED);
MovementMethod movementMethod = check.getMovementMethod();
if ((movementMethod == null) || !(movementMethod instanceof LinkMovementMethod)) {
if (check.getLinksClickable()) {
check.setMovementMethod(LinkMovementMethod.getInstance());
}
}
//Skipped unecassry codes
}
private void showDialog() {
internetDialog = new AlertDialog.Builder(NewsDetails.this)
...
}
private void loadNews() {
Log.d(TAG, "loadNews called");
final ProgressBar progressBar;
progressBar = (ProgressBar) findViewById(R.id.progress_circle);
progressBar.setVisibility(View.VISIBLE);
String news_id = getIntent().getStringExtra("NewsId");
Log.d(TAG, "You clicked news id " + news_id);
StringRequest stringRequest = new StringRequest(news_id,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.d("Debug", response.toString());
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
parseHtml(response);
newsData = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
final AlertDialog.Builder sthWrongAlert = new AlertDialog.Builder(NewsDetails.this);
...
sthWrongAlert.show();
}
});
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request queue
requestQueue.add(stringRequest);
}
private void parseHtml(String response) {
Log.d(TAG, "parsinghtml");
Document document = Jsoup.parse(response);
String news_title = document.select("h1.entry-title").first().text();
news_content = document.select("div.entry-content").first().html();
newsTitle.setText(news_title);
Spanned spanned = Html.fromHtml(news_content, new UILImageGetter(newsContent, this), null );
newsContent.setText(spanned);
//Unhiding views
newsTitle.setVisibility(View.VISIBLE);
newsContent.setVisibility(View.VISIBLE);
}
}
I have tried to pass String.valueOf(newsContent) to check.gatherLinksForText but it didn't work.
I have also tried check.gatherLinksForText(news_content) but it throws NPE.
Please what is the right parameter that I should pass check.gatherLinksForText() to make it work?
Related
I have created a separate class in which I have defined all about volley and in another activity, I have directly pass URL, CONTEXT and Get Response...
but in my NavDrawerActivity.java how do I call the subCategoryJSON(); method without writing my volley code again as I have done with mainCategoryJSON(); method in which I just simply pass the URL, method type.
Also is this a correct approach I am doing or there need to be some modification in the code, what I want is that wherever I am using API in my project and using volley for it, I don't have to write code again and again just simply pass the URL,method type
VolleyResponseListener.java
public interface VolleyResponseListener {
void onResponse(String response, String tag);
void onError(VolleyError error, String tag);
}
CustomStringRequestVolley.java
public class CustomStringRequestVolley {
private String url;
private String tag;
Context ctx;
private VolleyResponseListener volleyResponseListener;
public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
this.url = url;
this.tag = tag;
this.ctx=ctx;
this.volleyResponseListener = volleyResponseListener;
sendRequest();
}
private void sendRequest() {
final ProgressDialog pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Loading ...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("catresponse", "response " + response);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
volleyResponseListener.onResponse(response, tag);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);
}
}
NavDrawerActivity.java
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainCategoryJSON();
subCategoryJSON();
}
private void mainCategoryJSON() {
CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);
}
#Override
public void onResponse(String response, String tag) {
switch (tag) {
case "TAG1":
try {
Log.i("Responseeeeeezaq :", response.toString() + " " + tag);
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
CategoryModelClass categoryModelClass = new CategoryModelClass();
categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
categoryArrayList.add(categoryModelClass);
Log.d("zpuyi", String.valueOf(categoryArrayList));
}
categoryAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
VolleyLog.e("Error: ", error.getMessage());
}
private void subCategoryJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("subcategoryJsonResponse", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
You have written the answer correctly but you are not implementing the written custom volley class code in the activity class.
First Define the interface class for the Volley as below,
Now implement the volley interface in the java class where you have written the custom volley class as below:
CustomStringRequestVolley.java
public class CustomStringRequestVolley implements volleyCallback {
public Context context;
public CustomStringRequestVolley(Context context) {
this.context = context;
}
public interface volleyCallback {
void onSuccess(String result);
void onError(String error);
}
public void callGetServer(String URL, final
volleyCallback callback){
if (!checkInternetConnection(context)) {
showNoInternetDialogue(context);
return;
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}, error -> {
if (error.networkResponse == null){
if (error.getClass().equals(TimeoutError.class)){
Toast.makeText(context, "Timeout.Please try again",
Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NoConnectionError.class)){
Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NetworkError.class)) {
Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ParseError.class)){
Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ServerError.class)){
Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
}
else {
parseVolleyError(error);
}
}
}
) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
//setting up the retry policy for slower connections
int socketTimeout = 120000;//120000 milli seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Now use this Custom volley class in every activity you required. It reduces you
boilerplate code
NavDrawerActivity.java
CustomStringRequestVolley customStringRequestVolley;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point_navigation);
customStringRequestVolley = new CustomStringRequestVolley(this);
}
private void subCategoryJSON() {
customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String error) {
//show error code
}
});
}
Let me know after you try this #Abhishek
I want change the background color of of LinearLayout of Fragment A from Fragment B .These fragments are in same viewpager in sliding tabs.
The data of both fragment are dynamically changed from server.Here I have to click a textview of Fragment B then its linearlayout's color be changed manually(POST method) but due to net slow the background color of Fragment A (Because the textview of Fragment A is already selected so its color is already set.) is not removed from LinearLayout(GET method). But after sometime it will disappear .
So I want to set color manually till color is to be loaded. To make good user interface while clicking on textview for selection package.
MinPackageFragment
public class MinPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private View mView;
private TextView nepal_minimum_package_price, nepal_minimum_package_plan;
private LinearLayout nepal_minimum_package_linearlayout;
private String GET_NEPAL_MIN_PACKAGE_URL;
private String CHECK_CURRENT_PACKAGE_URL;
private WebView webview;
private String minPackagePrice;
private String minPackageItem;
private int THIS_ID;
private String CHOOSE_PACKAGE;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_min_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1001;
GET_NEPAL_MIN_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1001?token=" + token;
webview = (WebView) mView.findViewById(R.id.minimumNepaliListWebView);
webview.getSettings().setJavaScriptEnabled(true);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_minimum_package_price = mView.findViewById(R.id.nepal_minimum_package_price);
nepal_minimum_package_plan = mView.findViewById(R.id.nepal_minimum_package_plan);
nepal_minimum_package_linearlayout = mView.findViewById(R.id.nepal_minimum_package_linearlayout);
nepal_minimum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I want change here the background color of linearlayout of another fragment but getting error
showDialog();
choosePackage();
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setContentFromServer();
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
String avgprice = pref123.getString("mineprice", minPackagePrice);
String avgitems = pref123.getString("minitems", minPackageItem);
nepal_minimum_package_price.setText(avgprice);
webview.loadData(avgitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return mView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
Log.v("mydata1", data + "");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
hideDialog();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setContentFromServer() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_MIN_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = silver.getString("name");
minPackagePrice = silver.getString("price");
minPackageItem = silver.getString("includes");
if (getActivity() != null) {
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref123.edit();
editor.putString("mineprice", minPackagePrice);
editor.putString("minitems", minPackageItem);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
MaxPackageFragment
public class MaxPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private WebView maximumNepaliListWebView;
private View maxView;
private TextView nepal_maximum_package_plan, nepal_maximum_package_price;
private String GET_NEPAL_PACKAGE_URL;
private String maxPackageprice;
private String maxPackageitems;
private String CHECK_CURRENT_PACKAGE_URL;
private LinearLayout nepal_maximum_package_linearlayout;
private String CHOOSE_PACKAGE;
private int THIS_ID;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
maxView = inflater.inflate(R.layout.fragment_max_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1003;
GET_NEPAL_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1003?token=" + token;
nepal_maximum_package_linearlayout = maxView.findViewById(R.id.nepal_maximum_package_linearlayout);
maximumNepaliListWebView = maxView.findViewById(R.id.maximumNepaliListWebView);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_maximum_package_plan = maxView.findViewById(R.id.nepal_maximum_package_plan);
nepal_maximum_package_price = maxView.findViewById(R.id.nepal_maximum_package_price);
nepal_maximum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
// I want change here the background color of linearlayout of another fragment but getting error
choosePackage();
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setItemToLayout();
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
String maxprice = pref1.getString("maxprice", maxPackageprice);
String maxitems = pref1.getString("maxitems", maxPackageitems);
nepal_maximum_package_price.setText(maxprice);
maximumNepaliListWebView.loadData(maxitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return maxView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1003) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
hideDialog();
}
}
}
else {
JSONArray errordata = responceData.getJSONArray("errors");
String errormessage = errordata.getJSONObject(0).getString("message");
Toast.makeText(getActivity(), "" + errormessage, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setItemToLayout() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
Log.v("responceData", "onResponse: " + responceData);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = platinum.getString("name");
maxPackageprice = platinum.getString("price");
maxPackageitems = platinum.getString("includes");
if (getActivity() != null) {
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("maxprice", maxPackageprice);
editor.putString("maxitems", maxPackageitems);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID ==1003){
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
There are three fragments in same viewpager of fragment,within three tabs.
If your fragment is in same Activity, You can use the FragmentManager. findFragmentById(int id) which return by invoke Fragment.getFragmentManager() method to retrieve the reference of another fragment
then invoke the method to change the background color
Here is my code... which i displayed listview data... Now i want to fetch other details under this id
I want to fetch from database based on the Growers ID. Which is get from the listview
public class FarmerDetails extends Activity implements OnClickListener
{
private TextView tv;
private Button btnView;
private TextView textViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.farmerdetails);
btnView = (Button) findViewById(R.id.bView);
textViewResult = (TextView) findViewById(R.id.textViewResult);
btnView.setOnClickListener(this);
tv=(TextView) findViewById(R.id.tv1);
}
private void getData(final String value) {
Intent i = getIntent();
String code = i.getStringExtra("itemValue");
tv.setText("Grower's ID: "+code);
String url = Config.DATA_Details+tv.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(FarmerDetails.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
}
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String ccri="";
String name="";
String address="";
String taluk="";
String punch = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject farmerData = result.getJSONObject(0);
ccri=farmerData.getString(Config.KEY_CCRI);
name = farmerData.getString(Config.KEY_NAME);
address = farmerData.getString(Config.KEY_ADDRESS);
taluk = farmerData.getString(Config.KEY_TALUK);
punch=farmerData.getString(Config.KEY_PUNCH);
}
catch (JSONException e)
{
e.printStackTrace();
}
textViewResult.setText("CCRI Code:\t"+ccri+"Name:\t"+name+"\nAddress:\t" +address+ "\nTaluk:\t"+taluk+"\nPunchayat:\t"+punch);
}
#Override
public void onClick(View v) {
getData();
}
}
In my code only ID is displaying... fetching is not performing.. Plz help!!
this is kinda complicated.
you'll have to check out if ur url is right. Print the url in
console and type it in some browser do the GET request. If there's
no response, well it might be your problem. Maybe you did not
compose the url right.
if there's some response in step 1, ask the server guy what's going
on there. and wait.
My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);
I have an activity in which layout I have X checkboxes and X TextView.
Through "setText()" I am filling the TextViews with text parsed through JSON in a complex form (several values from several columns plus static text).
I would like to convert this answer in a string to be later added to an Arraylist but it turns out null (I think because of the quotation marks).
this is the average text I am parsing and "setText"ing:
public void showJSON(String response){
String One="";
String Two="";
String Three = "";
String Four = "";
try {
JSONObject jsonObject = new JSONObject(response4);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
One = collegeData.getString(Config.KEY_One);
Two = collegeData.getString(Config.KEY_Two);
Three = collegeData.getString(Config.KEY_Three);
Four = collegeData.getString(Config.KEY_Four);
} catch (JSONException e) {
e.printStackTrace();
}
textView.setText("One:\t"+One+"\nTwo:\t" +Two+ "\nThree: "+ Three+"\nFour:\t"+Four);
}
I tried newString = String.valueOf("One:\t"+One+"\nTwo:\t" +Two+ "\nThree: "+ Three+"\nFour:\t"+Four); right after the setText, but it returns a null.
With a String newString = ""; it also becomes a problem as I have quotation marks in the code as well.
It goes without saying that both String newString; and TextView textView; are declared at the beginning.
Any guess?
Complete code is as following
public class Popup1 extends Activity {
public TextView textViewResult;
public String newString;
public ArrayList<String> builder = new ArrayList<String>();
public CheckBox check;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup1);
textViewResult = (TextView) findViewById(R.id.textViewResult);
final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox);
checkView(checkBox1, "holacheck", newString);
isChecked(checkBox1, "holacheck");
getData();
}
public void checkView (final CheckBox view, final String key, final String newString) {
view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (view.isChecked()) {
KeySaver.saveShare(Popup1.this, key, view.isChecked());
builder.add((String.valueOf(newString)));
builder.add("\n");
} else {
KeySaver.removeKey(Popup1.this, key);
}
}
});
}
public void isChecked(final CheckBox view, String key){
if(view != null){
if(KeySaver.isExist(Popup1.this, key)){
view.setChecked(KeySaver.getBoolSavedShare(Popup1.this, key));
}else{
view.setChecked(false);
}
}
}
public void getData() {
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
StringRequest stringRequest = new StringRequest(Config.DATA_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Popup1.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showJSON(String response){
String One="";
String Two="";
String Three = "";
String Four = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
One = collegeData.getString(Config.KEY_One);
Two = collegeData.getString(Config.KEY_Two);
Three = collegeData.getString(Config.KEY_Three);
Four = collegeData.getString(Config.KEY_Four);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("One:\t" + One + "\nTwo:\t" + Two + "\nThree:\t" + Three + "\nFour:\t" + Four);
newString = String.valueOf("One:"+One+"Two:" +Two+ "Three:"+ Three+"Four:"+Four);
}
}
#Override
public void finish() {
String risultato = builder.toString().replace("[", "").replace("]", "");
// Prepare data intent
Intent data = new Intent();
data.putExtra("result", risultato);
setResult(1, data );
super.finish();
}
}
newString is null the first time you access it in onCreate() in the line:
checkView(checkBox1, "holacheck", newString);
This is because your data hadn't been retrieved yet at that point.
Make checkBox1 a class field, and move the checkView() call to the end of the showJSON() method.
private CheckBox checkBox1;
...
public void onCreate(Bundle savedInstanceState) {
...
checkBox1 = (CheckBox) findViewById(R.id.checkBox);
isChecked(checkBox1, "holacheck");
getData();
}
public void showJSON(String response){
...
textViewResult.setText("One:\t" + One + "\nTwo:\t" + Two + "\nThree:\t" + Three + "\nFour:\t" + Four);
newString = String.valueOf("One:"+One+"Two:" +Two+ "Three:"+ Three+"Four:"+Four);
checkView(checkBox1, "holacheck", newString);
}