Converting Asnyctask to volley [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
am new to android and am trying to convert the following asnyctask code to volley but getting a lot of errors advice on how to do it success fully
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost("http://192.168.0.2/testquiz/index.php");
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(QuizActivity.this, "Downloading Quiz","Wait....", true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
System.out.println("Resulted Value: " + result);
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
quizQuestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
*/
private List<QuizWrapper> returnParsedJsonObject(String result) {
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
jsonArray = resultObject.optJSONArray("quiz_questions");
}
catch (JSONException e) {
e.printStackTrace();
}
if (jsonArray != null) { // check jsonArray is null?
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String question = jsonChildNode.getString("question");
String answerOptions = jsonChildNode.getString("possible_answers");
int correctAnswer = jsonChildNode.getInt("correct_answer");
newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonObject;
}
here is what i have achieved so far any help will be appreciated
public Object getQuestion() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray questions = response.getJSONArray("questions");
for(int i=0; i<questions.length(); i++){
JSONObject quiz_questions = questions.getJSONObject(i);
String firstQuestion = quiz_questions.getString("firstQuestion");
String optionOne = quiz_questions.getString("optionOne");
String optionTwo = quiz_questions.getString("optionTwo");
String optionThree = quiz_questions.getString("optionThree");
String optionFour = quiz_questions.getString("optionFour");
quizQuestion.append(firstQuestion+ "" +optionOne+"" +optionTwo+""+optionThree+""+optionFour+ "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
return question;
}
the errors occuring
FATAL EXCEPTION: main
Process: test.com.okcupid, PID: 31544
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.com.okcupid/test.com.okcupid.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at test.com.okcupid.QuizActivity.getQuestion(QuizActivity.java:175)
at test.com.okcupid.QuizActivity.onCreate(QuizActivity.java:118)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

The problem is in this line:
requestQueue.add(jsonObjectRequest);
At the point it reaches the line requestQueue is null for some reason. You need to make sure the variable gets initialized before using it. If you're not able to be sure, then always wrap it with
if (requestQueue != null)
You need to take a quick tutorial on how multi threading works also. Because in getQuestion you kick off an asynchronous request (JsonObjectRequest), the lines after it (requestQueue.add(jsonObjectRequest) and the return statement) are going to be executed before onResponse

Related

JSON exception and permissions

I have written app for weather using open weather API.... but when i install the app in my phone and click on the button to determine weather it crashes... I use Android M in my phone
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
//combined the exceptions MalformedURL and IOException to a common to display a toast msg
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String msg = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for(int i = 0;i<arr.length();i++){
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String desc = "";
main = jsonPart.getString("main");
desc = jsonPart.getString("description");
icon = jsonPart.getString("icon");
if (main != "" && desc != "") {
msg += main + "\r\n" + desc;
}
}
if(msg != ""){
weatherReport.setText(msg);
}
else{
Toast.makeText(MainActivity.this,
"Location not able to determine",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(MainActivity.this,
"Location not able to determine",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
The error shown is that arr.length() is applied on a null array....
i don't get what the error is . is it about permissions ... if so how should i implement permissions in Marshmallow... this is the code that is inside onCreate(), if its about permissions pls tell how to implement..
try {
//to hide the keyboard after pressing the button
InputMethodManager manager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0);
DownloadTask downloadTask = new DownloadTask();
//used to encode the entered input for url.. for example San Fransisco appears in url
//as San%20Fransisco ... and to enable that we use the encoder...
String encodedCity = URLEncoder.encode(city,"UTF-8");
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Logcat ..
02-25 22:56:54.009 1413-1413/com.example.hemantj.weather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hemantj.weather, PID: 1413
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:133)
at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
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:5451)
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)
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString());
JSONArray array = jsonobj.getJSONArray("Staff_Details");
for (int i = 0; i < array.length(); i++) {
Clint_id = editText_user_name.getText().toString();
Api_key = array.getJSONObject(i).getString("api_key");
COMPANY_LOGO = array.getJSONObject(i).getString("company_logo");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
internet permission only
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
error is in your onPostExecute()
new JSONArray(weatherInfo); //is returning null
so arr is null
what is value of weatherInfo?

FORT SDK integration in 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

android jsonObject Null Pointer Exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am new to JSON. I need help. My android studio keeps on telling me that my jsonobject is NULL. I can parse and display my jsonarray into a listview. But when i click the page where i displayed it, my app crashes.
Parser
class BgTask extends AsyncTask<Void, Void, String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/result/hehe.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputstream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
}
}
public void publishGame(View view)
{
if(json_string == null)
{
Toast.makeText(getApplicationContext(), "Get Data First",Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, Games.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
}
code that posts
Bundle intent=getIntent().getExtras();
if(intent !=null) {
json_string = intent.getString("json_data");
json_string = getIntent().getExtras().getString("json_data");
}
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String team1, score1, team2, score2, Type;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
team1 = JO.getString("team1");
score1 = JO.getString("score1");
team2 = JO.getString("team2");
score2 = JO.getString("score2");
Type = JO.getString("Type");
Downloader downloader = new Downloader(team1, score1, team2, score2, Type);
gamesAdapter.add(downloader);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The error pointing is here try {
jsonObject = new JSONObject(json_string);
The error is because you are trying to parse "json_data" to JSONObject which is not a valid json. Perhaps you are having server response in a variable called json_data which is of String type if that is the case you need to pass that variable instead of passing String literal into JSONObject constructor.

Json Parsing from Url In Android , Not working

I am parsing data from URL , Its Getting below mentioned Error.
Raw Data is Showing Perfectly from Server.Not able to Split the Data Using Json Parsing.
Please help me solve this error
EDIT : 1
Json Response from URL
[
{
"ID": 4,
"Name": "Vinoth",
"Contact": "1111111111",
"Msg": "1"
},
{
"ID": 5,
"Name": "Mani",
"Contact": "22222222",
"Msg": "1"
},
{
"ID": 6,
"Name": "Manoj",
"Contact": "33333333333",
"Msg": "1"
}
]
Error :
org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err: at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity {
TextView name1,email,status,face;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.button1);
name1 = (TextView)findViewById(R.id.sname);
email = (TextView)findViewById(R.id.email);
status = (TextView)findViewById(R.id.status);
face = (TextView)findViewById(R.id.fb);
GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Server Request URL
String serverURL = "http://webapp/api/values";
// Create Object and call AsyncTask execute Method
new LoadService().execute(serverURL);
}
});
}
// Class with extends AsyncTask class
private class LoadService extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private final String TAG = null;
String name = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
// UI Element
uiUpdate.setText("");
Dialog.setMessage("Loading service..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
// NOTE: Don't call UI Element here.
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// Close progress dialog
Dialog.dismiss();
Log.e(TAG, "------------------------------------- Output: " + Content);
try {
JSONArray jArr=new JSONArray(Content);
for(int i=0;i<jArr.length();i++) {
JSONObject json=jArr.getJSONObject(i);
name1.setText(json.getString("Name"));
email.setText(json.getString("ID"));
status.setText(json.getString("Contact"));
face.setText(json.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("EXCEPTION ","");
}
uiUpdate.setText("Raw Output : " + Content);
}
}
}
As per your response is JSONArray and gson library is better to use while json data parsing so use below class to any type of data like that
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ApiData {
#SerializedName("data")
#Expose
private JsonArray Data;
public <T> List<T> getData(Class<T> c) {
Type type = new ListParams(c);
return new Gson().fromJson(Data, type);
}
private class ListParams implements ParameterizedType {
private Type type;
private ListParams(Type type) {
this.type = type;
}
#Override
public Type[] getActualTypeArguments() {
return new Type[]{type};
}
#Override
public Type getRawType() {
return ArrayList.class;
}
#Override
public Type getOwnerType() {
return null;
}
#Override
public boolean equals(Object o) {
return super.equals(o);
}
}
}
Create model class like :
public class Model{
String ID;
String Name;
String Contact;
String msg;
}
Now parse your data like:
ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class);
try {
Object jsonObject = new JSONTokener(Content).nextValue();
JSONArray jArr=new JSONArray(jsonObject );
for(int i=0;i<jArr.length();i++) {
JSONObject json=jArr.getJSONObject(i);
name1.setText(json.getString("Name"));
email.setText(json.getString("ID"));
status.setText(json.getString("Contact"));
face.setText(json.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("EXCEPTION ","");
}
Directly you cannot apply string to array, you should convert string to jsonobject ,then you can do object to array.
Hope you understand
As i have added escaping to your json here only for storing it temporary :
Please check below parsing code and it is working for me :
String response = "[\r\n {\r\n \"ID\": 4,\r\n \"Name\": \"Vinoth\",\r\n \"Contact\": \"1111111111\",\r\n \"Msg\": \"1\"\r\n },\r\n {\r\n \"ID\": 5,\r\n \"Name\": \"Mani\",\r\n \"Contact\": \"22222222\",\r\n \"Msg\": \"1\"\r\n },\r\n {\r\n \"ID\": 6,\r\n \"Name\": \"Manoj\",\r\n \"Contact\": \"33333333333\",\r\n \"Msg\": \"1\"\r\n }\r\n]";
try {
JSONArray jsonArray = new JSONArray(response); // replace response with your response string
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("ID", jsonObject.getInt("ID") + "");
Log.e("Name", jsonObject.getString("Name"));
Log.e("Contact", jsonObject.getString("Contact"));
Log.e("Msg", jsonObject.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Logs I have printed :
12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 4 12-17
15:42:54.459 9064-9064/com.example.testapplication E/Name: Vinoth
12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact:
1111111111 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/ID: 5 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Name: Mani 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Contact: 22222222 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459
9064-9064/com.example.testapplication E/ID: 6 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Name: Manoj 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Contact: 33333333333 12-17
15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1
Thanks ..!
The documentation of public JSONArray (String json) says it throws a
JSONException if the parse fails or doesn't yield a JSONArray.
Maybe he can't handle your response which is quite funny because a simple online json parser can: http://json.parser.online.fr/
As the user "Jelle van Es" mentioned in a previous comment, I would try Gson to do the work. (I would have commented under his comment but I have to few reputation xD)
You are using getString on "ID" when you should be using getInt. I tested the JSON string you provided in your question. The following code works:
String json =
"[{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Mani\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("ID");
String name = jsonObject.getString("Name");
String contact = jsonObject.getString("Contact");
String msg = jsonObject.getString("Msg");
System.out.println("id=" + id + ", name='" + name + "\', contact='" + contact + "\', msg='" + msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
Output from running the above code:
id=4, name='Vinoth', contact='1111111111', msg='1
id=5, name='Mani', contact='22222222', msg='1
id=6, name='Manoj', contact='33333333333', msg='1
If you are still getting an error, post the stacktrace.
Check this linkJSONArray
You should not directly use the response you get after hitting web service.First convert it to string as given in the link and also use getInt() when you are parsing your id
You can Parse your JSON like below.
try {
JSONArray _jArray = new JSONArray("YOUR_RESPONSE");
if (_jArray.length()>0){
for (int i = 0 ; i < _jArray.length();i++){
JSONObject _jSObject = _jArray.getJSONObject(i);
int ID = _jSObject.getInt("ID");
String Name = _jSObject.getString("Name");
String Contact = _jSObject.getString("Contact");
String Msg = _jSObject.getString("Msg");
System.out.println("Id : " + ID);
System.out.println("Name : " + Name);
System.out.println("Contact : " + Contact);
System.out.println("Msg : " + Msg);
}
}
} catch (Exception e) {
e.printStackTrace();
}
Best way and very fast parsing of JSON is GSON liabrary
dependacy for android studio compile 'com.google.code.gson:gson:2.3.1' OR you can download jar.
Make DTO names of all strings exactly same json of resonse.
Class ClassDTO{
String ID;
String Name;
String Contact;
String Msg;
take gettters & setters
}
Just include this lines in your code.
JSONArray array=new JSONArray(Content);
if (array.length() > 0) {
Gson gson = new Gson();
int i = 0;
while (i < array.length()) {
list.add(gson.fromJson(array.getJSONObject(i).toString(), ClassDTO.class));
i++;
}
} else {
Toast.makeText(JobCardActivity.this, "No response from server", Toast.LENGTH_LONG).show();
}
for json url hit and parsing of the data i have use this way
First i have created a class for Async request
public class AsyncRequestForActivities extends
AsyncTask<String, Integer, String> {
OnAsyncRequestComplete caller;
Context context;
String method = "POST";
List<NameValuePair> parameters = null;
ProgressDialog pDialog = null;
String Progress_msg;
// Three Constructors
public AsyncRequestForActivities(Context a, String m, String Msg,
List<NameValuePair> p) {
caller = (OnAsyncRequestComplete) a;
context = a;
method = m;
parameters = p;
Progress_msg = Msg;
}
public AsyncRequestForActivities(Context a, String m) {
caller = (OnAsyncRequestComplete) a;
context = a;
method = m;
}
public AsyncRequestForActivities(Context a) {
caller = (OnAsyncRequestComplete) a;
context = a;
}
// Interface to be implemented by calling activity
public interface OnAsyncRequestComplete {
public void asyncResponse(String response);
}
public String doInBackground(String... urls) {
// get url pointing to entry point of API
String address = urls[0].toString();
if (method == "POST") {
return post(address);
}
if (method == "GET") {
return get(address);
}
return null;
}
public void onPreExecute() {
pDialog = new ProgressDialog(context);
pDialog.setMessage(Progress_msg); // typically you will
pDialog.setCancelable(false); // define such
// strings in a remote file.
pDialog.show();
}
public void onProgressUpdate(Integer... progress) {
// you can implement some progressBar and update it in this record
// setProgressPercent(progress[0]);
}
public void onPostExecute(String response) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
caller.asyncResponse(response);
}
protected void onCancelled(String response) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
caller.asyncResponse(response);
}
#SuppressWarnings("deprecation")
private String get(String address) {
try {
if (parameters != null) {
String query = "";
String EQ = "=";
String AMP = "&";
for (NameValuePair param : parameters) {
query += param.getName() + EQ
+ URLEncoder.encode(param.getValue()) + AMP;
}
if (query != "") {
address += "?" + query;
}
}
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(address);
HttpResponse response = client.execute(get);
return stringifyResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
private String post(String address) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
if (parameters != null) {
post.setEntity(new UrlEncodedFormEntity(parameters));
}
HttpResponse response = client.execute(post);
return stringifyResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
private String stringifyResponse(HttpResponse response) {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
now when you want to get Data you have to implement the interface in your activity
public class SomeClass extends Activity implements OnAsyncRequestComplete{
// your activity code here
// some where in class in any function you want
AsyncRequestForActivities req=new AsyncRequestForActivities(SomeClass.this, MethodType, YourMessage,
Perameters_in_List<NameValuePareType>);
req.execute(YourURL);
}//end of that function
#Override
public void asyncResponse(String response) {
try {
if (!(response == null)) {
JSONArray jArray = new JSONArray("response");
if (jArray.length()>0){
for (int i = 0 ; i < jArray.length();i++){
JSONObject jSObject = jArray.getJSONObject(i);
int ID = _jSObject.getInt("ID");
String Name = _jSObject.getString("Name");
String Contact = jSObject.getString("Contact");
String Msg = jSObject.getString("Msg");
System.out.println("Id : " + ID);
System.out.println("Name : " + Name);
System.out.println("Contact : " + Contact);
System.out.println("Msg : " + Msg);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Progress Bar not visible with Stand alone asynctask

I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}

Categories

Resources