FORT SDK integration in android - android

I want to integrate payment in my app for which I used the "FORT" sdk. I did follow the documentation on the "payfort.com" website but when I integrated the library my app crashed.
this is the error-output:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.newsolution.jiibli, PID: 12133
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.newsolution.jiibli/com.payfort.fort.android.sdk.activities.InitSecureConnectionActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:223)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:343)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:312)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:277)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.payfort.fort.android.sdk.activities.InitSecureConnectionActivity.onCreate(InitSecureConnectionActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6877)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
at android.app.ActivityThread.access$1100(ActivityThread.java:223) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7223) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

in Manifest.xml: I make style extend from AppCompactTheme
<activity android:name=".Activity.PaymentMethod"
android:theme="#style/AppTheme"/>
in gradle import the library
compile project(':FORTSDKv1.2')
I start PaymentMethod Activity with intent for result:
call method pay();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
setContentView(R.layout.activity_payment_method);
fortCallback = FortCallback.Factory.create();
pay();
}
public void pay() {
try {
ProviderInstaller.installIfNeeded(getApplicationContext());
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
new sdkToken().execute();// get SDK Token and pass it to paid method
}
class sdkToken extends AsyncTask<String, Void, String> {
public sdkToken() {
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
signature = getSignature();
String jsonRequestString = "{\"access_code\" : \""+access_code+"\" " +
", \"service_command\" : \"SDK_TOKEN\", \"language\" : \"en\","
+ "\"merchant_identifier\" : \""+merchant_identifier+"\", \"signature\" : \"" + signature + "\", "
+ "\"device_id\" : \"" + FortSdk.getDeviceId(PaymentMethod.this) + "\"}";
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// Instantiate the custom HttpClient
HttpClient httpclient = new MyHttpClient(httpParameters, getApplicationContext());
// DefaultHttpClient httpclient =new DefaultHttpClient();
HttpPost request = new HttpPost("https://sbpaymentservices.payfort.com/FortAPI/paymentApi");
StringEntity param = null;
try {
param = new StringEntity(jsonRequestString);// Setup Http POST entity with JSON String
// Setup request type as JSON
request.addHeader("content-type", "application/json");
request.setEntity(param);
HttpResponse response = null;
response = httpclient.execute(request); // Post request to FORT
sb = new StringBuilder(); // Read response using StringBuilder
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return "" + sb.toString();
}
protected void onPostExecute(String fortResponse) {
super.onPostExecute(fortResponse);
if (fortResponse != null) {
JSONObject jsonObject = null;
System.out.println(sb.toString());
try {
jsonObject = new JSONObject(fortResponse);
sdk_token = jsonObject.getString("sdk_token");
System.out.println(sdk_token);
progressBar.setVisibility(View.GONE);
paid(sdk_token);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
progressBar.setVisibility(View.GONE);
Log.i("fortResponse", " fortResponse==null");
Toast.makeText(activity, getString(R.string.compatible), Toast.LENGTH_LONG).show();
}
}
}
private void paid(String sdk_token) {
fortRequest = new FortRequest();
Map<String, String> requestMap = new HashMap<>();
requestMap.put("merchant_reference", random());
requestMap.put("language", "en");
requestMap.put("order_description", "android");
requestMap.put("currency", "SAR");
requestMap.put("amount", "100");
requestMap.put("command", "AUTHORIZATION");//PURCHASE
requestMap.put("customer_name", "add any name");
requestMap.put("eci", "ECOMMERCE");
requestMap.put("customer_email", "add email");
requestMap.put("sdk_token", sdk_token);
fortRequest.setShowResponsePage(true);
fortRequest.setRequestMap(requestMap);
try {
FortSdk.getInstance().registerCallback(this, fortRequest, FortSdk.ENVIRONMENT.TEST, 5, fortCallback,
new FortInterfaces.OnTnxProcessed() {
#Override
public void onCancel(Map<String, String> requestParamsMap, Map<String,
String> responseMap) {
//TODO: handle me
JSONObject responseObject = new JSONObject(responseMap);
try {
String response_message = responseObject.getString("response_message");
paymentType = 0;
Toast.makeText(PaymentMethod.this, "" + response_message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onSuccess(Map<String, String> requestParamsMap, Map<String,
String> fortResponseMap) {
System.out.println("success requestParamsMap " + requestParamsMap);
System.out.println("success fortResponseMap " + fortResponseMap);
JSONObject responseObject = new JSONObject(fortResponseMap);
try {
String response_message = responseObject.getString("response_message");
Toast.makeText(PaymentMethod.this, "" + response_message, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("cardNo", cardNo);
intent.putExtra("cardId", cardId);
setResult(2, intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Map<String, String> requestParamsMap, Map<String,
String> fortResponseMap) {
System.out.println("requestParamsMap " + requestParamsMap);
System.out.println("fortResponseMap " + fortResponseMap);
JSONObject responseObject = new JSONObject(fortResponseMap);
try {
String response_message = responseObject.getString("response_message");
Toast.makeText(PaymentMethod.this, response_message, Toast.LENGTH_LONG).show();
Intent intent = new Intent(PaymentMethod.this, PayFail.class);
intent.putExtra("cardNo", cardNo);
intent.putExtra("cardType", cardType);
intent.putExtra("cardPersonName", cardPersonName);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
fortCallback.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
Log.i("exception", e.getMessage());
}
}
private String getSignature() {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
String text = "sadafdfeeeeaccess_code="+access_code+"
+ "device_id=" + FortSdk.getDeviceId(PaymentMethod.this)
+ "language=enmerchant_identifier="+merchant_identifier"+service_command=SDK_TOKENsadafdfeeee";
md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed
} catch (Exception e) {
e.printStackTrace();
}
byte[] digest = md.digest();
signature = String.format("%064x", new java.math.BigInteger(1, digest));
return signature;
}
public static String random() {
SecureRandom secureRandom = new SecureRandom();
return new BigInteger(40, secureRandom).toString(32);
}

What did the trick is, manifest file is conflicting with payfort sdk, you have to you use overide manifest in application tag

Related

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

Image displaying on imageview crashes app

I used glide for displaying image from url.When i used the debugger the url contains the image.But the problem is when ever the app run it closes.Is there any thing to do in code of imageview?Please help me to recover this problem.Forgive me if i asked blunder.Thanks in advance.My code is provided below.
public class ProductImages extends AsyncTask<Void , Void, Void> {
int status;StringBuilder sb;
String strJson, postData;
JSONArray jsonArray;
String msg;
boolean pass=false;
ArrayList<String> imgurls=new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
String url =getResources().getString(R.string.url) + "WebServices/WebService.asmx/ProductImages";
HttpURLConnection c = null;
try {
postData = "{\"productID\":\"" + productID + "\",\"TID\":\"" + constants.TID + "\"}";
String response=db.GetResponses(url,postData);
if(!response.equals("")){
strJson=response;
}
else {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-type", "application/json; charset=utf-16");
c.setRequestProperty("Content-length", Integer.toString(postData.length()));
c.setDoInput(true);
c.setDoOutput(true);
c.setUseCaches(false);
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
DataOutputStream wr = new DataOutputStream(c.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
status = c.getResponseCode();
switch (status) {
case 200:
case 201: BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
int a=sb.indexOf("[");
int b=sb.lastIndexOf("]");
strJson=sb.substring(a, b + 1);
// strJson=cryptography.Decrypt(strJson);
strJson="{\"JSON\":" + strJson.replace("\\\"","\"").replace("\\\\","\\") + "}";
}
}
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
msg=ex.getMessage();
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
msg=ex.getMessage();
}
}
}
if(strJson!=null)
{try {
JSONObject jsonRootObject = new JSONObject(strJson);
jsonArray = jsonRootObject.optJSONArray("JSON");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
msg=jsonObject.optString("Message");
pass=jsonObject.optBoolean("Flag",true);
imgurls.add(getResources().getString(R.string.url) + jsonObject.optString("Image").substring((jsonObject.optString("Image")).indexOf("Media")));
if(jsonObject.optBoolean("IsMain")){
productImage=getResources().getString(R.string.url) + jsonObject.optString("Image").substring((jsonObject.optString("Image")).indexOf("Media"));
}
}
if(pass){
if(c!=null)
db.ResponsesSaving(url,postData,strJson,"null");
}
} catch (Exception ex) {
msg=ex.getMessage();
}}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(!pass) {
new AlertDialog.Builder(EnquiryItem.this).setIcon(android.R.drawable.ic_dialog_alert)//.setTitle("")
.setMessage(msg)
.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setCancelable(false).show();
}
else {
for (int i=0;i<imgurls.size();i++) {
final int fi=i;
ImageView imageView = (ImageView) findViewById(R.id.image);
Glide.with(EnquiryItem.this).load(imgurls).into(imageView);
}
}
}
**My image view**
<ImageView
android:id="#+id/image"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_above="#+id/textView22"
android:layout_alignLeft="#+id/textView22"
android:layout_alignStart="#+id/textView22"
android:layout_gravity="center"
android:layout_marginBottom="16dp"
android:background="#drawable/back"
Logcat
java.lang.IllegalArgumentException: Unknown type class java.util.ArrayList. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class
at com.bumptech.glide.RequestManager.loadGeneric(RequestManager.java:629)
at com.bumptech.glide.RequestManager.load(RequestManager.java:598)
at com.tech.test.testapp.EnquiryItem$ProductImages.onPostExecute(EnquiryItem.java:524)
at com.tech.test.testapp.EnquiryItem$ProductImages.onPostExecute(EnquiryItem.java:412)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Glide need not have declare GlideModule in AndroidMinifest.xml. You just need to following steps:
YourGlideModule extends AppGlideModule, you can override function applyOptions in the YourGlideModule class.
You should make project in android studio -> build -> make project, it will generate the GlideApp class.
Use the GlideApp such as
GlideApp.with(this)
.load(imagegUrl)
.into(imageview)

Android JSON Parsing View Gujarati Character Using Web Service

View Gujarati Character Using Web Service in Android JSON Parsing
I Got Gujarati Word Like the one in the images I've included. If Gujarati Word is presented like અપૂર્વ, then it appears like the 1st rounded circle in the image.
Please help me to find a solution to this question
Image For Getting Gujarati Word Like this can be seen below:
And here is my code :
public class GetProductData extends AsyncTask<String, String, JSONObject> {
//private ProgressDialog p_dialog;
JSONArray jArray;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*p_dialog = new ProgressDialog(con);
p_dialog.setMessage("Please Wait ...");
p_dialog.setIndeterminate(false);
p_dialog.setCancelable(false);
p_dialog.show();*/
}
#Override
protected JSONObject doInBackground(String... params) {
jArray = JSONParser.GetProductData();
Log.d("TAG", "JSON ARRAY FOR DEVICE ID : " + jArray);
String msg = "Nothing Happened...";
try {
if (jArray != null) {
Key = jArray.getJSONObject(0).getString("Key").toString();
if (Key.equals("1")) {
db.deleteAllProductDetails();
for (int i = 1; i < jArray.length(); i++) {
Log.d("ADADADADTAG","CategoryName ::: "+jArray.getJSONObject(i).getString("CategoryName"));
Log.d("ADADADADTAG","SubCategoryName ::: "+jArray.getJSONObject(i).getString("SubCategoryName").trim());
Log.d("ADADADADTAG","ProductName ::: "+jArray.getJSONObject(i).getString("ProductName"));
db.insertProductDetails(
jArray.getJSONObject(i).getString("ProductId").trim(),
jArray.getJSONObject(i).getString("CategoryId").trim(),
jArray.getJSONObject(i).getString("CategoryName").trim(),
jArray.getJSONObject(i).getString("CategoryImageUrl").trim(),
jArray.getJSONObject(i).getString("SubCategoryId").trim(),
jArray.getJSONObject(i).getString("SubCategoryName").trim(),
jArray.getJSONObject(i).getString("SubCategoryImageUrl").trim(),
jArray.getJSONObject(i).getString("ProductName").trim(),
jArray.getJSONObject(i).getString("ProductImageUrl").trim(),
jArray.getJSONObject(i).getString("ProductCode").trim(),
jArray.getJSONObject(i).getString("ProductPrice").trim(),
jArray.getJSONObject(i).getString("ProductUnit").trim(),
jArray.getJSONObject(i).getString("ProductSmallDesc").trim(),
jArray.getJSONObject(i).getString("CategoryStatus").trim(),
jArray.getJSONObject(i).getString("SubCategoryStatus").trim(),
jArray.getJSONObject(i).getString("ProductStatus").trim()
);
}
}
} else {
}
} catch (Exception e) {
// TODO: handle exception
Log.e("TAG", "Warn :" + e.getLocalizedMessage());
Log.e("TAG", "Warn :" + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
super.onPostExecute(json);
// p_dialog.dismiss();
if (jArray != null) {
if (Key.equals("1")) {
Cursor cGetAllProductDetails = db.getAllProductDetails();
//Toast.makeText(con,"Count ::: "+cGetAllProductDetails.getCount(),Toast.LENGTH_LONG).show();
preferences = con.getSharedPreferences(IsLogin,Context.MODE_PRIVATE);
if(preferences.getBoolean(IsLogin,false))
{
Intent i = new Intent(con, DashboardActivityEnglishWithLogin.class);
startActivity(i);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finish();
}
else
{
Intent i = new Intent(con, DashboardActivityEnglishWithoutLogin.class);
startActivity(i);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finish();
}
} else if (Key.equals("0")) {
} else {
}
}
}
}
public static JSONArray GetProductData() {
// TODO Auto-generated method stub
try
{
init();
url = SITE_URL + "GetProductData";
Log.d("TAG", url);
httpPost = new HttpPost(url.toString());
Log.d("TAG", "HTTP POST"+httpPost);
pairs = new ArrayList<NameValuePair>();
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
Log.d("TAG", "HTTP POST"+httpPost);
httpResponse = httpClient.execute(httpPost);
Log.d("TAG", "HTTP RESPONSE"+httpResponse);
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
/* Convert response to string */
result = getResult(inputStream);
Log.d("TAG","RESULT : "+ result);
jsonArray = new JSONArray(result);
Log.d("TAG", "JSON ARRAY : "+ jsonArray);
} catch (ClientProtocolException e) {
Log.e("TAG", "Error in Client Protocol : " + e.toString());
} catch (JSONException e) {
Log.e("TAG", "Error Parsing data " + e.toString());
} catch (Exception e) {
Log.e("TAG", "Error in HTTP Connection : " + e.toString());
}
return jsonArray;
}
Parse Json data using URLDecoder,
URLDecoder.decode(jArray.getJSONObject(i).getString("CategoryName"), "utf-8");
Try this
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://floming.com/shayri/guj_romanse.json", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();

E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException LIST VIEW

I am trying to generate List View from JSON response but unable to do it.
Getting error at line: "list_view.setAdapter(customAdapter);" #onPostExecute
NullPointerException on above line...
Complete code:
public class Screen2 extends AppCompatActivity {
ProgressDialog pDialog;
ArrayList<Information> record_list;
ListView list_view;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
record_list=new ArrayList<Information>();
list_view=(ListView) findViewById(R.id.list_view);
new Test().execute();
}
public class Test extends AsyncTask<String, Void, ArrayList<Information>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Screen2.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected ArrayList<Information> doInBackground(String... params) {
if(record_list.size()>0){record_list.clear();}
String jsonStr = makeServiceCall();
//ssen = new ArrayList<Information>();
try {
//HashMap<String,String> hashMap=new HashMap<>();
JSONArray jsonArray=new JSONArray(jsonStr);
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("label");
String email = jsonObject.getString("email");
Information information = new Information(id, name, email);
System.out.println("id: " + id + "name:" + name + "email" + email);
record_list.add(information);
}
System.out.println(jsonStr);
return record_list;
//return record_list;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Information> s) {
super.onPostExecute(s);
for(int i=0;i<record_list.size();i++){
System.out.println(record_list.get(i));
}
if(record_list!=null && !record_list.isEmpty()){
customAdapter=new CustomAdapter(Screen2.this,record_list);
list_view.setAdapter(customAdapter);
}
else {
Toast.makeText(Screen2.this, "Array List is Empty", Toast.LENGTH_SHORT).show();
}
//ListAdapter listAdapter1=new ArrayAdapter<String>(Screen2.this,R.layout.custom_row,record_list);
//list_view.setAdapter(listAdapter);
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
}
public String makeServiceCall(){
String response = null;
try {
URL url = new URL("http://192.168.1.127:9000/tasks2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (IOException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (Exception e) {
System.out.println("MalformedURLException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb);
return sb.toString();
}
}
}
Please go through the Stack Trace for the above code...
It will be very much helpful for me if anyone resolves this issue.
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.hariprasad.healthpassportnew1.Screen2$Test.onPostExecute(Screen2.java:99)
at com.example.hariprasad.healthpassportnew1.Screen2$Test.onPostExecute(Screen2.java:51)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Maybe your record_list is null
so please add
if (record_list.size > 0) {
list_view.setAdapter(customAdapter);
}
and also before adding the data in record_list make clear
put this code before String jsonStr = makeServiceCall();
if (record_list.size > 0) {
record_list.clear();
}

Camera intent and Async Task's doInBackground clashes

In my activity i have an AsyncTask, in which i had overridden doInBackGround.
In the same activity i have a camera intent to open the camera and allow user to take a pic
The problem is when i call the camera intent it is triggering the doInBackGround method i overrode. Which eventually gives me a SingleClientConnManager exception which asks me to release the client before allocating it again.
Here is my activity code:
public class UserProfileActivity extends Activity {
//many instance fiels here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
new LongOperation().execute("");
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
changeImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsLabel = (TextView) findViewById(R.id.userFriends_profile);
changeImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
//Point 1
}
});
//Point 2
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
private ProgressDialog dialog = new ProgressDialog(context);
#Override
protected String doInBackground(String... params) {
//Point 3
try {
HttpResponse response;
HttpPost httppost = new HttpPost(
"http://www.xxxxx.com/yyyy/zzzz");
//httpclient is global to maintain sessions
response = SignUpActivity.httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("error in reading input stream", e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
email = jObj.getString("email");
clickedUserId = jObj.getInt("user_id");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
friendsIds = new int[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
friendsIds[i] = friendsJsonArray.getJSONObject(i)
.getInt("user_id");
}
adapter = new ArrayAdapter<String>(context,
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
Log.d("error in creating json object", e.toString());
}
} catch (Exception e) {
//Point 5
Log.e("error main try", "Error in http connection" + e.toString());
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
changeImage.setText("Change image");
editInfo.setText("Edit");
friendsLabel.setText("Friends");
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
userImage.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
e1.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
} catch (IOException e2) {
e2.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Point 4
if (resultCode == RESULT_OK) {
if (data != null) {
photo = (Bitmap) data.getExtras().get("data");
userImage.setImageBitmap(photo);
}else{
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
}
}
here in the code Point 1, 2, 3, 4, 5 gives the sequence of code flow once i click the changeImage TextView.
Please help me in solving this scenario.
Thank You.
If I am correct the problem is because of your device orientation get changed when you open camera.That calls your activity's onCreate() method again
please insert this line to your activity in menifest that is causing problem
<activity
android:name="your activity" android:configChanges="keyboardHidden|orientation"
/>

Categories

Resources