database connection with asynctask error - android

Hi I'm beginner at android so I hope that you would help me in details
I made connection to MySQL database with AsyncTask it's all good it connects well and I get my data from the database but the thing is when I turn off my database (database is on wamp) my app force closes and it gives this error:java.util.concurrent.timeoutexception
I will put the AsyncTask codes below
private void get_banners(final int pages) {
AsyncHttpPost post = new AsyncHttpPost("http://192.168.1.102/soton/new.php");
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City", MainActivity.sp.getString("City", ""));
body.addStringPart("Page", String.valueOf(pages));
body.addStringPart("Cate", "all");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if (e != null) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
if (!result.equals("")) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//you can toast the result here
//Toast.makeText(MainActivity.activity, result,Toast.LENGTH_LONG).show();
if (page == 0) {
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String, Object> hash_add = new HashMap<>();
hash_add.put("ID", object.getString("ID"));
hash_add.put("Username", object.getString("Username"));
hash_add.put("Title", object.getString("Title"));
hash_add.put("Description", object.getString("Description"));
hash_add.put("Price", object.getString("Price"));
hash_add.put("Tell", object.getString("Tell"));
hash_add.put("Email", object.getString("Email"));
hash_add.put("City", object.getString("City"));
hash_add.put("Cate", object.getString("Cate"));
hash_add.put("Img1", object.getString("Img1"));
hash_add.put("Img2", object.getString("Img2"));
hash_add.put("Img3", object.getString("Img3"));
hash_add.put("Date", object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
else {
Toast.makeText(MainActivity.activity,result,Toast.LENGTH_LONG).show();
}
}
});
}
Update: Stack Trace
FATAL EXCEPTION: AsyncServer
Process: com.morteza.newproject, PID: 3211
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.morteza.newproject.Frag_banners_all$3.onCompleted(Frag_banners_all.java:145)
at com.morteza.newproject.Frag_banners_all$3.onCompleted(Frag_banners_all.java:130)
at com.koushikdutta.async.http.AsyncHttpClient.invokeWithAffinity(AsyncHttpClient.java:527)
at com.koushikdutta.async.http.AsyncHttpClient.access$800(AsyncHttpClient.java:51)
at com.koushikdutta.async.http.AsyncHttpClient$7.run(AsyncHttpClient.java:534)
at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)
at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)
at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)
at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)
at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)
W/System.err: java.util.concurrent.TimeoutException
W/System.err: at com.koushikdutta.async.http.AsyncHttpClient$2.run(AsyncHttpClient.java:246)
W/System.err: at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)
W/System.err: at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)
W/System.err: at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)
W/System.err: at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)
W/System.err: at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)
Application terminated.

Problem soved i solved it by adding only an else to the code the currect code is below
private void get_banners(final int pages) {
AsyncHttpPost post = new AsyncHttpPost("http://192.168.1.102/soton/new.php");
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City", MainActivity.sp.getString("City", ""));
body.addStringPart("Page", String.valueOf(pages));
body.addStringPart("Cate", "all");
post.setBody(body);
try {
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if (e != null) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity, "server is offline", Toast.LENGTH_LONG).show();
e.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
//this is the answer
else {
if (!result.equals("")) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//you can toast the result here
//Toast.makeText(MainActivity.activity, result,Toast.LENGTH_LONG).show();
if (page == 0) {
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String, Object> hash_add = new HashMap<>();
hash_add.put("ID", object.getString("ID"));
hash_add.put("Username", object.getString("Username"));
hash_add.put("Title", object.getString("Title"));
hash_add.put("Description", object.getString("Description"));
hash_add.put("Price", object.getString("Price"));
hash_add.put("Tell", object.getString("Tell"));
hash_add.put("Email", object.getString("Email"));
hash_add.put("City", object.getString("City"));
hash_add.put("Cate", object.getString("Cate"));
hash_add.put("Img1", object.getString("Img1"));
hash_add.put("Img2", object.getString("Img2"));
hash_add.put("Img3", object.getString("Img3"));
hash_add.put("Date", object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(MainActivity.activity, result, Toast.LENGTH_LONG).show();
}
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}

Related

Scan Bar code and read it from JSON after store it in recyclerView

//1.I am trying to pass Bar code value using ZXingScannerView scanner
//2. Then if scanned bar code is equals to JSON barcode object show item_name and cost from the JSON //file inside recyclerview, My issue is after scanning nothing is showing
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
scannerView = (ZXingScannerView) view.findViewById(R.id.zxscan);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
scannerView.setResultHandler(SecondFragment.this);
scannerView.startCamera();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getActivity(), "Please Accept The Permission", Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
})
.check();
return view;
}
#Override
public void onDestroy() {
scannerView.stopCamera();
super.onDestroy();
}
#Override
public void handleResult(Result rawResult) {
processRawResult(rawResult.getText());
if (Patterns.WEB_URL.matcher(rawResult.getText()).matches()) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(rawResult.getText()));
startActivity(browserIntent);
}
}
private void processRawResult(String text) {
if (text.startsWith("BEGIN:")){
String[] tokens = text.split("\n");
QRVCardModel qrvCardModel = new QRVCardModel();
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].startsWith("BEGIN:")) {
qrvCardModel.setType(tokens[i].substring("BEGIN:".length()));
}
else if (tokens[i].startsWith("N")) {
qrvCardModel.setName(tokens[i].substring("N:".length()));
}
else if (tokens[i].startsWith("ORG")) {
qrvCardModel.setOrg(tokens[i].substring("ORG:".length()));
}
else if (tokens[i].startsWith("TEL:")) {
qrvCardModel.setTel(tokens[i].substring("TEL:".length()));
}
else if (tokens[i].startsWith("URL:")) {
qrvCardModel.setUrl(tokens[i].substring("URL:".length()));
}
else if (tokens[i].startsWith("EMAIL:")) {
qrvCardModel.setEmail(tokens[i].substring("EMAIL:".length()));
}
else if (tokens[i].startsWith("ADS:")) {
qrvCardModel.setEmail(tokens[i].substring("ADS:".length()));
}
else if (tokens[i].startsWith("NOTE:")) {
qrvCardModel.setNote(tokens[i].substring("NOTE:".length()));
}
else if (tokens[i].startsWith("SUMMERY:")) {
qrvCardModel.setSummer(tokens[i].substring("SUMMERY:".length()));
}
else if (tokens[i].startsWith("DTSTART:")) {
qrvCardModel.setDtstart(tokens[i].substring("DTSTART:".length()));
}
else if (tokens[i].startsWith("DTEND:")) {
qrvCardModel.setDtend(tokens[i].substring("DTEND:".length()));
}
}
}
else if (text.startsWith("hhtp://")||
text.startsWith("hhtps://")||
text.startsWith("www."))
{
QRURLMode qrurlMode = new QRURLMode(text);
}
else if (text.startsWith("geo:"))
{
QRGeoModel qrGeoModel= new QRGeoModel();
String delims = "[ ,?q= ] +";
String tokens[]= text.split(delims);
for (int i=0; i< tokens.length;i++)
{
if (tokens[i].startsWith("geo:"))
{
qrGeoModel.setLat(tokens[i].substring("geo:".length()));
}
}
qrGeoModel.setLat(tokens[0].substring("geo".length()));
qrGeoModel.setLng(tokens[1]);
qrGeoModel.setGeo_place(tokens[2]);
}
else
{
Toast.makeText(getActivity(),"QR CODE PASS", Toast.LENGTH_SHORT).show();
String json;
try {
InputStream is = getActivity().getAssets().open("products.json");
Toast.makeText(getActivity(), "JSON1", Toast.LENGTH_SHORT).show();
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//Toast.makeText(getActivity(),"JSON2", Toast.LENGTH_SHORT).show();
json = new String(buffer, "UTF-8");
Log.d("JSONTestLogs", "JSON Raw Text: " + json);
JSONObject object = new JSONObject(json);
JSONArray productsArray = object.getJSONArray("products");
Log.d("JSONTestLogs", "Fetching the Products array from JSON File. Size: " + productsArray.length());
for (int i = 0; i < productsArray.length(); i++) {
JSONObject item = productsArray.getJSONObject(i);
Log.d("JSONTestLogs", "Item: " + i + "\n" + item.toString());
if (text.equals(item.getString("bar_code"))) {
products_name.add(item.getString("item_name"));
cost.add(item.getString("cost"));
}
}
}
catch
(IOException e)
{
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace(); }
}
scannerView.resumeCameraPreview(SecondFragment.this);
// Toast.makeText(getActivity(),"JSON3", Toast.LENGTH_SHORT).show();
}
}
after you scanned the barcode. I think add the barcode to your list here;
products_name.add(item.getString("item_name"));
After add operation, you did not refresh the recyclerview data.
This code part working just one time.
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
you should call this part again or you need a function inside your adapter which is notify the data of recyclerview.

Arraylist as argument in Interface occur NullPointer Exception in Android RecyclerViewAdapter

I tried to Pass String and ArrayList as an argument value through an interface from RecyclerViewAdapter to fragment, Data loading in recycler perfectly, But When I try to select the particular item in the list it leads to NullPointerException. Here is my code which is Implemented, Please help to fix my issue, I was stumbling with this issue for the whole day.
Interface
public interface QikMsgTemplateListener {
void onTemplateSelectedDesc(String templateId, String templateName, String templateDesc, String templateScript, ArrayList<HashMap<String, String>> preClipList, ArrayList<HashMap<String, String>> postClipList);
}
RecyclerViewAdapter Class
public class QikRecTemplateAdapter extends RecyclerView.Adapter{
private QikMsgTemplateListener mQikMsgTemplateListener;
//Constructor
public QikRecTemplateAdapter(Activity activity,QikMsgTemplateListener listener, List<TemplateModel> templateList, String mSelectedTemplateName) {
this.mTemplateList = templateList;
this.mActivity = activity;
this.mQikMsgTemplateListener = listener;
this.selectedTempName = mSelectedTemplateName;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #NonNull int position) {
//OnClickListener
mHolder.mButtonTempSelect.setOnClickListener(v -> {
TemplateModel mTemplateModel = mTemplateList.get(mPosition);
String templateId = mTemplateModel.getTemplateId()!=null?mTemplateModel.getTemplateId():"";
String templatename = mTemplateModel.getTemplateName()!=null? mTemplateModel.getTemplateName():"";
String templateDesc = mTemplateModel.getTemplateDesc()!=null?mTemplateModel.getTemplateDesc():"";
String templateScript = mTemplateModel.getTemplateScript()!=null?mTemplateModel.getTemplateScript():"";
ArrayList<HashMap<String, String>> mSelectedPreClipList=new ArrayList<HashMap<String, String>>();
if(mTemplateModel.getPreClipList()!=null){
mSelectedPreClipList.clear();
mSelectedPreClipList = mTemplateModel.getPreClipList();
}
ArrayList<HashMap<String, String>> mSelectedPostClipList=new ArrayList<HashMap<String, String>>();
if(mTemplateModel.getPostClipList()!=null){
mSelectedPostClipList.clear();
mSelectedPostClipList = mTemplateModel.getPostClipList();
}
/*CallBack values pass to QikRecTemplateAdapter*/
//here facing null pointer
if (mTemplateModel.getPreClipList() != null && mTemplateModel.getPostClipList() != null) {
mQikMsgTemplateListener.onTemplateSelectedDesc(templateId, templatename, templateDesc, templateScript, mSelectedPreClipList, mSelectedPostClipList);
} else if (mTemplateModel.getPreClipList() != null && mTemplateModel.getPostClipList() == null) {
mQikMsgTemplateListener.onTemplateSelectedDesc(templateId, templatename, templateDesc, templateScript, mSelectedPreClipList, null);
} else if (mTemplateModel.getPostClipList() == null && mTemplateModel.getPostClipList() != null) {
mQikMsgTemplateListener.onTemplateSelectedDesc(templateId, templatename, templateDesc, templateScript, null, mSelectedPostClipList);
} else if (mTemplateModel.getPostClipList() == null && mTemplateModel.getPostClipList() == null) {
mQikMsgTemplateListener.onTemplateSelectedDesc(templateId, templatename, templateDesc, templateScript, null, null);
}
});
}
}
Fragment Class
public class TemplatesFragment extends Fragment implements View.OnClickListener, QikMsgTemplateListener {
ArrayList<HashMap<String, String>> mPreClipList = new ArrayList<>();
ArrayList<HashMap<String, String>> mPostClipList = new ArrayList<>();
List<TemplateModel> templateList=new ArrayList<>();
#Nullable
QikRecTemplateAdapter mQikRecTemplateAdapter=null;
//All other initalitzing steps
/*==========Invoke Lifecycle Methods==========*/
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof QikMsgTemplateListener){
mQikMsgTemplateListener=(QikMsgTemplateListener) context;
}else{
throw new RuntimeException(context.toString()
+ " must implement QikMsgTemplateListener");
}
}
#Override
public void onDetach() {
super.onDetach();
try {
if (mQikMsgTemplateListener != null) {
mQikMsgTemplateListener = null;
}
}catch (Exception ex){ex.printStackTrace();}
}
#Override
public void onResume() {
super.onResume();
getAPIValues();
}
#Override
public void onClick(#NonNull View v) {
switch (v.getId()) {
/*==========Action To Pass Values to Activity==========*/
case R.id.txtVw_done_template:
/*CallBack values pass to Activity*/
Objects.requireNonNull(mQikMsgTemplateListener).onTemplateSelectedDesc(this.selectedTemplateId, this.temp_name,this.selectedTemplateDesc,this.selectedTemplateScript,this.mPreClipList,this.mPostClipList);
Fragment mPresentDoneFragment=this;
try {
Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction().remove(mPresentDoneFragment).commit();
}catch (Exception ex){ex.printStackTrace();}finally {
mPresentDoneFragment=null;
}
break;
default:
break;
}
}
#Override
public void onTemplateSelectedDesc(String templateId, String templateName, String templateDesc, String templateScript,
ArrayList<HashMap<String, String>> argPreClipList, ArrayList<HashMap<String, String>> argPostClipList) {
try {
if (!templateId.isEmpty()) {
this.temp_name = templateName;
this.selectedTemplateId = templateId;
this.selectedTemplateDesc = templateDesc;
this.selectedTemplateScript = templateScript;
/*Here Values comes Empty or 0 when i put try catch in AdapterClass*/
if(argPreClipList!=null){
this.mPreClipList = argPreClipList;
}
if(argPostClipList!=null){
this.mPostClipList = argPostClipList;
}
}
}catch (Exception ex){ex.printStackTrace();}
}
void getAPIValues(){
JSONObject mResponseObj=null;
//ArrayList<HashMap<String, String>> mPreClipList = new ArrayList<>();
//ArrayList<HashMap<String, String>> mPostClipList = new ArrayList<>();
boolean hasHeader=false;
boolean hasFooter=false;
boolean canPostComments=false;
boolean canTakeSurvey=false;
boolean doNotAutoPublish=false;
boolean doNotArchive=false;
try {
templateList.clear();
mResponseObj=new JSONObject(getResponse);
try {
String str_json_status = mResponseObj.optString(AppResponseTags.TAG_JSON_STATUS);
if (str_json_status.equalsIgnoreCase(AppResponseTags.TAG_RESPONSE_SUCCESS)) {
JSONObject clientResponse_obj = mResponseObj.optJSONObject(AppResponseTags.TAG_CLIENTRESPONSE);
String str_totalRecords = clientResponse_obj.optString(AppResponseTags.TAG_TOTALRECORDS);
JSONArray templateContent = clientResponse_obj.optJSONArray(AppResponseTags.TAG_DATA);
try {
if (!clientResponse_obj.isNull(AppResponseTags.TAG_DATA))
for (int templateCount = 0; templateCount < templateContent.length(); templateCount++) {
JSONObject templateContent_Obj = templateContent.optJSONObject(templateCount);
try {
if (!templateContent_Obj.isNull(AppResponseTags.TAG_ID)) {
str_templateId = templateContent_Obj.optString(AppResponseTags.TAG_ID);
} else {
str_templateId = "";
}
if (!templateContent_Obj.isNull(AppResponseTags.TAG_NAME)) {
str_templateName = templateContent_Obj.optString(AppResponseTags.TAG_NAME);
} else {
str_templateName = "";
}
if (!templateContent_Obj.isNull(AppResponseTags.TAG_PRESIGNEDTHUMBNAILURL)) {
str_templateImage = templateContent_Obj.optString(AppResponseTags.TAG_PRESIGNEDTHUMBNAILURL);
} else {
str_templateImage = "";
}
if(!templateContent_Obj.isNull(AppResponseTags.TAG_DESCRIPTION)){
description=templateContent_Obj.optString(AppResponseTags.TAG_DESCRIPTION);
}else{
description="";
}
if(!templateContent_Obj.isNull(AppResponseTags.TAG_SCRIPT)){
scriptTxt=templateContent_Obj.optString(AppResponseTags.TAG_SCRIPT);
}else{
scriptTxt="";
}
ArrayList<HashMap<String, String>> mTempPreClipList = new ArrayList<>();
ArrayList<HashMap<String, String>> mTempPostClipList = new ArrayList<>();
if(!templateContent_Obj.isNull(AppResponseTags.TAG_PRECLIPS)) {
JSONArray mPreClipArray =new JSONArray();
mPreClipArray = templateContent_Obj.optJSONArray(AppResponseTags.TAG_PRECLIPS);
try {
if (mPreClipArray != null && mPreClipArray.length() > 0) {
try {
System.out.println("*-------------------*********--------------------------*");
for (int i = 0; i < mPreClipArray.length(); i++) {
HashMap<String, String> map = new HashMap<>();
try {
JSONObject dataObject = mPreClipArray.getJSONObject(i);
String mPreContenId = dataObject.getString(AppResponseTags.TAG_CONTENTID);
map.put("preclipid", mPreContenId);
mTempPreClipList.add(map);
} catch (Exception ex) {
ex.printStackTrace();
}finally {
map=null;
}
System.out.println(str_templateName+"->"+"Array-Pos-PreClip-"+i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
//mPreClipList = null;
mPreClipArray = null;
}
System.out.println("*-----------------------------------------------------------------------*");
System.out.println(str_templateName+"->"+"Array-Pos-PreClip Array-" + mTempPreClipList.size());
System.out.println("*---------------------========================--------------------------*");
}
if(!templateContent_Obj.isNull(AppResponseTags.TAG_POSTCLIPS)) {
JSONArray mPostClipArray =new JSONArray();
mPostClipArray = templateContent_Obj.getJSONArray(AppResponseTags.TAG_POSTCLIPS);
try {
if (mPostClipArray != null && mPostClipArray.length() > 0) {
try {
for (int i = 0; i < mPostClipArray.length(); i++) {
HashMap<String, String> map = new HashMap<>();
JSONObject dataObject = mPostClipArray.getJSONObject(i);
try {
String mPostContenId = dataObject.getString(AppResponseTags.TAG_CONTENTID);
map.put("postclipid", mPostContenId);
mTempPostClipList.add(map);
} catch (Exception ex) {
ex.printStackTrace();
}finally {
map=null;
}
System.out.println(str_templateName+"->"+"Array-Pos-PostClip-"+i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
//mPostClipList = null;
mPostClipArray = null;
}
System.out.println("*-----------------------------------------------------------------------*");
System.out.println(str_templateName+"->"+"Array-Pos-PostClip Array-" + mTempPostClipList.size());
System.out.println("*---------------------========================--------------------------*");
}
templateList.add(new TemplateModel(str_templateId, str_templateName, str_templateImage, temp_name,description,scriptTxt,mCallToActionType,mCallToActionLink,mCallToActionText,mAuthorEmailSignature, hasHeader, hasFooter, canPostComments, canTakeSurvey, doNotAutoPublish, doNotArchive, mChannelList,mTempPreClipList,mTempPostClipList));
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (templateList.size() > 0) {
mQikRecTemplateAdapter = new QikRecTemplateAdapter(getActivityContext, templateList, this, temp_name);
rcyVw_ChooseTemplate.setAdapter(mQikRecTemplateAdapter);
rcyVw_ChooseTemplate.setVisibility(View.VISIBLE);
rcyVw_ChooseTemplate.getAdapter().notifyDataSetChanged();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}catch (Exception ex){ex.printStackTrace();}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
StackTrace
W/System.err: java.lang.NullPointerException: Attempt to invoke interface method 'void com.ibot.cyranoapp.interfaces.quickmessage.QikMsgTemplateListener.onTemplateSelectedDesc(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList)' on a null object reference
W/System.err: at com.ibot.cyranoapp.adapters.quickrecord.QikRecTemplateAdapter.lambda$onBindViewHolder$0(QikRecTemplateAdapter.java:279)
W/System.err: at com.ibot.cyranoapp.adapters.quickrecord.-$$Lambda$QikRecTemplateAdapter$oPCYWC6_gHETxZtfdm5pQwAQTow.onClick(lambda)
W/System.err: at android.view.View.performClick(View.java:6205)
W/System.err: at android.widget.TextView.performClick(TextView.java:11103)
W/System.err: at android.widget.CompoundButton.performClick(CompoundButton.java:130)
W/System.err: at android.view.View$PerformClick.run(View.java:23653)
W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6682)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
In this code I added comment for better explanation about my issue. Thanks in Advance.
You mismatched the parameters when initiating your adapter. Your listener should be the second paramter
I think your listener is not getting initialized properly, and therefore it's throwing NullPointerException.
Try creating a setter for your listener and initialize on your TemplatesFragment's onCreateView() method:
public class QikRecTemplateAdapter extends RecyclerView.Adapter{
private QikMsgTemplateListener mQikMsgTemplateListener;
public void setQikMsgTemplateListener(QikMsgTemplateListener listener){
mQikMsgTemplateListener = listener;
}
...
...
}
public class TemplatesFragment extends Fragment implements View.OnClickListener, QikMsgTemplateListener {
ArrayList<HashMap<String, String>> mPreClipList = new ArrayList<>();
ArrayList<HashMap<String, String>> mPostClipList = new ArrayList<>();
....
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
//Initialize adapter before setting the listener.
qikRecTemplateAdapter.setQikMsgTemplateListener(this)
...
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
if(qikRecTemplateAdapter != null)
qikRecTemplateAdapter.setQikMsgTemplateListener(null)
super.onDetach();
}
}
Also, to avoid NullPointerException, always place a null safety check wherever you use it.

AsyncHttpPost force close when there is not internet

I used fragment in my application and when there is not internet app getting force close . I don't know what can I do . please help me
this code works perfect but when internet lost the application get error and force close
i use method to check internet by ping but it makes my app too slow
public static void get_detail(final int pages){
MainActivity.logo11.setImageResource(R.drawable.loading);
AsyncHttpPost post = new AsyncHttpPost(
"domain"
);
post.setTimeout(30000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City",MainActivity.sp.getString("City",null));
body.addStringPart("Cate","all");
body.addStringPart("Page", String.valueOf(pages));
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if(e != null){
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity,"network error",Toast.LENGTH_LONG).show();
refresh.setRefreshing(false);
e.printStackTrace();
}
});
}
if(!result.equals("")){
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.logo11.setImageResource(R.drawable.logo);
if(page==0){
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0 ;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String , Object> hash_add = new HashMap<String, Object>();
hash_add.put("ID",object.getString("ID"));
hash_add.put("Username",object.getString("Username"));
hash_add.put("Title",object.getString("Title"));
hash_add.put("Descript",object.getString("Descript"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
refresh.setRefreshing(false);
}catch (Exception e){
e.printStackTrace();
}
}
});
}else {
Toast.makeText(MainActivity.activity,"error",Toast.LENGTH_LONG).show();
}
}
});
}

Progress dialog dismisses before the view is displayed in the gridview

I start my progress dialog in oncreate method of fragment before is initiate my web request call. In the web request call, if I fetch the response and if its success I call the notifydatasetchanged method to refresh the adapter . But the dialog gets dismissed lot before the view is updated . Please help .
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pd = ProgressDialog.show(getActivity(), "Loading...", "Please Wait...");
getProducts(highPrice, lowPrice, isLowtoHigh);
}
private void getProducts(String highPrice,String lowPrice,String isLowtoHigh) {
// loadingDialog.loading();
APIRequst.getProductsCategory(getActivity().getApplicationContext(), isLowtoHigh, lowPrice, highPrice, new APIRequestListner() {
#Override
public void onSuccess(String response) {
if (response == null || response.isEmpty()) {
Log.e("orderhistory", "success but empty");
} else {
Log.e("products", response);
try {
JSONObject mainObj = new JSONObject(response);
boolean result = mainObj.has("is_success") && mainObj.getBoolean("is_success");
String resultMessage = mainObj.getString("message");
if (resultMessage.equalsIgnoreCase("Success")) {
if (result) {
productItems.clear();
adptProductItems.clear();
JSONArray jsonOrderList = mainObj.has("categories") ? mainObj.getJSONArray("categories") : null;
if (jsonOrderList != null) {
for (int i = 0; i < jsonOrderList.length(); i++) {
JSONObject jsonObj = jsonOrderList.getJSONObject(i);
ProductListItem newItem = (new Gson()).fromJson(jsonObj.toString(), ProductListItem.class);
productItems.add(newItem);
}
adptProductItems.notifyDataSetChanged();
pd.dismiss();
}
}
} else {
if (resultMessage.equalsIgnoreCase("No Value")) {
if (pd.isShowing())
pd.dismiss();
productItems.clear();
adptProductItems.notifyDataSetChanged();
Toast.makeText(getActivity(), "Sorry no prducts to display", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// adapter.notifyDataSetChanged();
}
#Override
public void onFailure() {
if (pd.isShowing())
pd.dismiss();
// loadingDialog.dismissDialog();
}
});
}
try to move " pd.dismiss();" below onFailure()
#Override
public void onFailure() {
if (pd.isShowing())
pd.dismiss();
// loadingDialog.dismissDialog();
}
pd.dismiss();
and
adptProductItems.notifyDataSetChanged();
//pd.dismiss(); remove fromhere
may it will help as I did in my case..

RichRelevance SDK internally giving Null Pointer Exception. How to fix it?

// method to set the richRelevance configuration
public static void initializeRichRelevance(Context context) {
final SharedPreference sharedPreference = SharedPreference.getInstance(context);
ClientConfiguration config = new ClientConfiguration(APIKEY, CLIENTKEY);
config.setApiClientSecret("");
Log.e("Member_ID",getStringValue(sharedPreference.getSharedPref("member_id")));
config.setUserId(getStringValue(sharedPreference.getSharedPref("member_id")));
config.setSessionId(UUID.randomUUID().toString());
RichRelevance.init(context, config);
// Enable all logging
RichRelevance.setLoggingLevel(RRLog.VERBOSE);
Logger.logDebug("RichRelevance", "initilization Done...");
}
// method to fetch recommended product from richRelevance
private void initRichRelevance() {
RichRelevance.setLoggingLevel(RRLog.VERBOSE);
Placement placement = new Placement(Placement.PlacementType.ITEM, "recs_2mh");
PlacementsRecommendationsBuilder placementsRecommendationsBuilder = new PlacementsRecommendationsBuilder();
placementsRecommendationsBuilder.setPlacements(placement);
placementsRecommendationsBuilder.setProductIds(idProduct);
placementsRecommendationsBuilder.setCallback(new Callback<PlacementResponseInfo>() {
#Override
public void onResult(PlacementResponseInfo placementResponseInfo) {
JSONObject jsonObject = null;
if (placementResponseInfo != null && placementResponseInfo.getPlacements() != null) {
try {
jsonObject = new JSONObject(placementResponseInfo.getRawJson().toString());
requestAPI(jsonObject);
} catch (JSONException e) {
Utils.logExceptionCrashLytics(e);
Logger.logError("JsonException", e.getMessage());
}
}
}
#Override
public void onError(com.richrelevance.Error error) {
Log.e(getClass().getSimpleName(), "Error: " + error.getMessage());
}
}).execute();
}
Fatal Exception: java.lang.NullPointerException
at com.richrelevance.internal.net.HttpUrlConnectionExecutor.getConnection(HttpUrlConnectionExecutor.java:87)
at com.richrelevance.internal.net.HttpUrlConnectionExecutor.execute(HttpUrlConnectionExecutor.java:40)
at com.richrelevance.internal.net.WebRequestManager.execute(WebRequestManager.java:172)
at com.richrelevance.internal.net.WebRequestManager$1.run(WebRequestManager.java:193)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at com.richrelevance.internal.net.WebRequestManager$2$1.run(WebRequestManager.java:219)
at java.lang.Thread.run(Thread.java:841)

Categories

Resources