An error occurred while executing doInBackground() Caused by: java.util.NoSuchElementException - java

I'm building an android app where in this section it pulls data from sql database as per the logged in userId(memberNo) which is passed through Bundle and shows it on a RecyclerView but i get this error:
2022-03-31 14:09:41.027 9620-9667/com.dennisky.kofee E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.dennisky.kofee, PID: 9620
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:759)
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:780)
at com.dennisky.kofee.MedicalFeesReports$RepData.packReportData(MedicalFeesReports.java:76)
at com.dennisky.kofee.MedicalFeesReports$MedicalReportDownloader.reportData(MedicalFeesReports.java:153)
at com.dennisky.kofee.MedicalFeesReports$MedicalReportDownloader.doInBackground(MedicalFeesReports.java:126)
at com.dennisky.kofee.MedicalFeesReports$MedicalReportDownloader.doInBackground(MedicalFeesReports.java:98)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
at java.lang.Thread.run(Thread.java:764) 
The Code that is executed when the error occurs is:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.dennisky.kofee.MedicalFeesReport.Parser;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
public class MedicalFeesReports extends AppCompatActivity {
RecyclerView recyclerView;
String ulrAddress = "http://10.0.2.2/important/loan_statements";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medical_fees_reports);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
new MedicalReportDownloader(MedicalFeesReports.this, ulrAddress, recyclerView).execute();
}
public String reportNumber() {
String member = null;
Bundle extra = getIntent().getExtras();
if (extra != null) {
member = extra.getString("memberNo");
}
return member;
}
public class RepData {
public String packReportData() {
JSONObject jo = new JSONObject();
StringBuffer jsonData = new StringBuffer();
try {
jo.put("MEMBER_NO", reportNumber());
Boolean isFirstValue = true;
Iterator it = jo.keys();
do {
String keys = it.next().toString();
String values = jo.get(keys).toString();
if (isFirstValue)
isFirstValue = false;
else
jsonData.append("&");
jsonData.append(URLEncoder.encode(keys, "UTF-8"));
jsonData.append("=");
jsonData.append(URLEncoder.encode(values, "UTF-8"));
} while (it.hasNext());
return jsonData.toString();
} catch (JSONException e) {
e.printStackTrace();
return "ERROR: DATA ERROR";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "ERROR: ERROR ENCODING DATA";
}
}
}
public class MedicalReportDownloader extends AsyncTask<Void, Void, String> {
Context context;
String urlAddress;
RecyclerView recyclerView;
ProgressDialog dialog;
public MedicalReportDownloader(Context context, String urlAddress, RecyclerView recyclerView) {
this.context = context;
this.urlAddress = urlAddress;
this.recyclerView = recyclerView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setTitle("Loading");
dialog.setMessage("fetching data, please wait...");
if (isFinishing() && dialog != null)
dialog.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.repData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();
if (s != null) {
Parser parser = new Parser(s, context, recyclerView);
parser.execute();
} else {
Toast.makeText(context, "No loan data found", Toast.LENGTH_SHORT).show();
}
}
private String repData() {
Object connection = Connector.connect(urlAddress);
if (connection.toString().startsWith("Error"))
return connection.toString();
try {
HttpURLConnection con = (HttpURLConnection) connection;
OutputStream stream = new BufferedOutputStream(con.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
String kiloData = new RepData().packReportData();
if (kiloData.startsWith("ERROR"))
return "ERROR: DATA ERROR";
writer.write(kiloData);
writer.flush();
writer.close();
InputStream inputStream = new BufferedInputStream(con.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer buffer = new StringBuffer();
if (bufferedReader != null) {
while ((line = bufferedReader.readLine()) != null)
buffer.append(line + "\n");
} else
return null;
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "ERROR: IO ERROR";
}
}
}
the mentioned parser class:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Parser extends AsyncTask<Void, Void, Integer> {
String data;
Context context;
RecyclerView recyclerView;
ProgressDialog dialog;
ArrayList<ReportData> reportData = new ArrayList<>();
MyAdapterMedicalReport adapter;
public Parser(String data, Context context, RecyclerView recyclerView) {
this.data = data;
this.context = context;
this.recyclerView = recyclerView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setTitle("Parsing data");
dialog.setMessage("Data parsing, please wait...");
dialog.show();
}
#Override
protected Integer doInBackground(Void... voids) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (dialog != null && dialog.isShowing()){
dialog.dismiss();
dialog = null;
}
if (integer == 1){
adapter = new MyAdapterMedicalReport(context, reportData);
recyclerView.setAdapter(adapter);
}else
Toast.makeText(context, "No Loan data found.", Toast.LENGTH_LONG).show();
}
private int parse(){
try {
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = null;
reportData.clear();
ReportData data = null;
for (int i = 0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
String loan_type = jsonObject.getString("loan_type");
String amount = jsonObject.getString("amount");
String data_approved = jsonObject.getString("date_approved");
String loan_status = jsonObject.getString("loan_status");
data = new ReportData();
data.setLoanType(loan_type);
data.setAmount(amount);
data.setDateApproved(data_approved);
data.setLoanStatus(loan_status);
reportData.add(data);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
How can i get through this error?

In your "packReportData()" method you're doing a "do..while" but you need to check if "it.hasNext() == true" BEFORE "it.next()" or it will crash as you saw.
Please convert "do...while" in a "while(it.hasNext()) {...}"

Related

AndroidStudio Login using REST servlet and oracle

I want to make Login Activity using eclipse servlet(REST file) and oracle.
I want to compare column value of EMAIL, PASS of table EMPLOYEES to EditText(user input email and password).
How can I compare two input Strings to column of database table?
This is LoginActivity file(MainActivity)
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity{
EditText email_txt, pw_txt;
Button login_btn;
String REST_URL = "http://localhost:8080/url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email_txt = (EditText)findViewById(R.id.email_txt);
pw_txt = (EditText)findViewById(R.id.pw_txt);
login_btn = (Button)findViewById(R.id.login_btn);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String useremail = email_txt.getText().toString();
String userpass = pw_txt.getText().toString();
//I want to fill this below
//
}
});
}
#Override
public void onResume() {
super.onResume();
JSONClient toServer;
toServer = new JSONClient((JSONClient.MyCallbackInterface) this);
toServer.execute(REST_URL, "GET", "");
}
}
This is JSONClient(Activity)
public class JSONClient extends AsyncTask<String, Void, JSONObject> {
private MyCallbackInterface mCallback;
public JSONClient(MyCallbackInterface callback) {
mCallback = callback;
}
#Override
protected JSONObject doInBackground(String... params) {
String url = params[0];
String method = params[1];
String content = params[2];
return getJSONFromUrl(url, method, content);
}
#Override
protected void onPostExecute(JSONObject result) {
mCallback.onRequestComplete(result);
}
public interface MyCallbackInterface {
public void onRequestComplete(JSONObject result);
}
public JSONObject getJSONFromUrl(String urlStr, String method, String content) {
JSONObject jObj = new JSONObject();
try {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setConnectTimeout(3000);
if (content != null && content.length() > 0) {
urlConnection.getOutputStream().write(content.getBytes(StandardCharsets.UTF_8));
}
String respStr = getStringFromInputStream(urlConnection.getInputStream());
Log.d("JSON Parser1", "Response from server: " + respStr);
jObj = new JSONObject(respStr);
} catch (Exception e) {
Log.e("JSON Parser Exception", e.getLocalizedMessage());
}
return jObj;
}
private String getStringFromInputStream(InputStream is) {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
Log.e("JSON Client", "Error while reading response from server");
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
Log.e("JSON Client", "Error while making string from HTTP response");
return null;
}
}
}
return sb.toString();
}
}

identify incoming caller android and display in toast

I'm trying to build a simple phonebook application where I can perform a search and an API will return the information. So far this is the part that I've got working.
I also want incoming caller to be identified with the same API, that would require the incoming number from Broastcastreceiver to be put into the API query and the returned information should be displayed in a toast. This is the part I'm having problems with.
So far this is what I have. Apologize if its really messy, this is what I've been playing around with recently and made small adjustments. Also its alot of copy-paste, I'm a beginner at java/Android and trying to learn.
HttpHandler.java
package se.xx.api_test;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler extends PhoneCallReceiver {
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();
}
}
PhoneCallReceiver.java
package se.xx.api_test;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.util.Log;
public class PhoneCallReceiver extends BroadcastReceiver {
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
public static String savedNumber; //because the passed incoming is only valid in ringing
#Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start){}
protected void onOutgoingCallStarted(Context ctx, String number, Date start){}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onMissedCall(Context ctx, String number, Date start){}
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if(lastState == state){
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
}
else if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
else{
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
}
MainActivity.java
package se.xx.api_test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
public class MainActivity extends AppCompatActivity {
private TextView tv;
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
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);
tv = (TextView) findViewById(R.id.textInput);
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
contactList.clear();
new GetContacts().execute();
}
});
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
String id = tv.getText().toString();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+id;
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("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// 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);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "namn","avdelning","mobil", "telnr"},
new int[]{R.id.email, R.id.mobile, R.id.mobil, R.id.telnr});
lv.setAdapter(adapter);
}
}
}
CallReceiver.java (this is what I've been playing around with)
package se.xx.api_test;
import java.util.Date;
import java.util.HashMap;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import android.widget.ListAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.lang.String;
import android.telephony.TelephonyManager;
public class CallReceiver extends PhoneCallReceiver {
#Override
public void onIncomingCallStarted(Context ctx, String number, Date start) {
final String phnr = String.valueOf(R.id.mobile);
Toast toast = Toast.makeText(ctx.getApplicationContext(), , Toast.LENGTH_SHORT);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(25);
toast.show();
}
#Override
public void onOutgoingCallStarted(Context ctx, String number, Date start) {
}
#Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onMissedCall(Context ctx, String number, Date start) {
}
private class APICall extends MainActivity {
String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
protected Void doInBackground(Void... arg0) {
String TAG = MainActivity.class.getSimpleName();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+number;
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("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
final String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// 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;
}
}
}
which part you got an error ?
with your Api ? or while receive you phone number from service ?
put your error to clarify the situation

I have taken text from JSON format of an API now I want to add image to it from same API in my android app

I'm new to android and finding it tough to update realtime text and images from API's in JSON format. I've successfully added text to my listview. Now I want to add image beside it. Thanks in advance.
MainActivity.java file
package com.example.android.samplelayout;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.net.Uri;
import android.graphics.drawable.Drawable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
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();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://webhose.io/search?token=9c55cbb1-2f1c-4700-9c1e-67e685152506&format=json&q=Indian%20Startup";
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
//JSONObject responseObject = jsonObj.getJSONObject("response");
JSONArray responseArray = jsonObj.getJSONArray("posts");
// looping through All Contacts
for (int i = 0; i < responseArray.length(); i++) {
JSONObject firstObject = responseArray.getJSONObject(i);
//JSONObject titleObject = firstObject.getJSONObject("title");
// Extract out the title, time, and tsunami values
//String image = firstObject.getString("main_image");
String title = firstObject.getString("title");
// tmp hash map for single contact
HashMap<String , String> contact = new HashMap<>();
// adding each child node to HashMap key => value
//contact.put("pic", image);
contact.put("name", title);
// 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);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,R.layout.list_item, new String[]{"name"}, new int[]{ R.id.name});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java file
package com.example.android.samplelayout;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
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();
}
}
I would suggest using a library that automatically puts an Image into an ImageView only using the Url of the image you want to use. Picasso would be a good Library for your use. You have to fetch the Image URL off the Json object and load it into the ImageView using Picasso's load().into()

Null pointer exception: invoking virtual method

i am trying to design a basic chat app. The app is build without any errors but as soon as i click any button on the emulator the app crashes and the log shows the following error:
07-01 22:50:39.367 30016-30032/com.example.ibm_admin.chat E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
07-01 22:50:39.367 30016-30032/com.example.ibm_admin.chat E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
07-01 22:50:39.370 30016-30016/com.example.ibm_admin.chat D/AndroidRuntime﹕ Shutting down VM
07-01 22:50:39.370 30016-30016/com.example.ibm_admin.chat E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ibm_admin.chat, PID: 30016
java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.example.ibm_admin.chat.UserFragment$Load.onPostExecute(UserFragment.java:84)
at com.example.ibm_admin.chat.UserFragment$Load.onPostExecute(UserFragment.java:71)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
07-01 22:50:40.975 30016-30023/com.example.ibm_admin.chat W/art﹕ Suspending all threads took: 15.530ms
07-01 22:51:02.766 30016-30023/com.example.ibm_admin.chat W/art﹕ Suspending all threads took: 6.893ms
MainActivity.java
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
public class MainActivity extends Activity {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String SENDER_ID = "Your Project Number";
static final String TAG = "L2C";
GoogleCloudMessaging gcm;
SharedPreferences prefs;
Context context;
String regid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("Chat", 0);
context = getApplicationContext();
if(!prefs.getString("REG_FROM","").isEmpty()){
Fragment user = new UserFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, user);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}else if(!prefs.getString("REG_ID", "").isEmpty()){
Fragment reg = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, reg);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}else if(checkPlayServices()){
new Register().execute();
}else{
Toast.makeText(getApplicationContext(),"This device is not supported",Toast.LENGTH_SHORT).show();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
private class Register extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
regid = gcm.register(SENDER_ID);
Log.e("RegId",regid);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("REG_ID", regid);
edit.commit();
}
return regid;
} catch (IOException ex) {
Log.e("Error", ex.getMessage());
return "Fails";
}
}
#Override
protected void onPostExecute(String json) {
Fragment reg = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, reg);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
}
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jAry = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if(params != null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public JSONArray getJSONArray(String url,List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSS",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jAry = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jAry;
}
}
LoginFragment.java
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LoginFragment extends Fragment {
SharedPreferences prefs;
EditText name, mobno;
Button login;
List<NameValuePair> params;
ProgressDialog progress;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, container, false);
prefs = getActivity().getSharedPreferences("Chat", 0);
name = (EditText)view.findViewById(R.id.name);
mobno = (EditText)view.findViewById(R.id.mobno);
login = (Button)view.findViewById(R.id.log_btn);
progress = new ProgressDialog(getActivity());
progress.setMessage("Registering ...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress.show();
SharedPreferences.Editor edit = prefs.edit();
edit.putString("REG_FROM", mobno.getText().toString());
edit.putString("FROM_NAME", name.getText().toString());
edit.commit();
new Login().execute();
}
});
return view;
}
private class Login extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... args) {
JSONParser json = new JSONParser();
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name.getText().toString()));
params.add(new BasicNameValuePair("mobno", mobno.getText().toString()));
params.add((new BasicNameValuePair("reg_id",prefs.getString("REG_ID",""))));
JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2:8080/login",params);
return jObj;
}
#Override
protected void onPostExecute(JSONObject json) {
progress.dismiss();
try {
String res = json.getString("response");
if(res.equals("Sucessfully Registered")) {
Fragment reg = new UserFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, reg);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}else{
Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
UserFragment.java
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class UserFragment extends Fragment {
ListView list;
ArrayList<HashMap<String, String>> users = new ArrayList<HashMap<String, String>>();
Button refresh,logout;
List<NameValuePair> params;
SharedPreferences prefs;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.user_fragment, container, false);
prefs = getActivity().getSharedPreferences("Chat", 0);
list = (ListView)view.findViewById(R.id.listView);
refresh = (Button)view.findViewById(R.id.refresh);
logout = (Button)view.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Logout().execute();
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.content_frame)).commit();
Fragment reg = new UserFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, reg);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
new Load().execute();
return view;
}
private class Load extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... args) {
JSONParser json = new JSONParser();
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
JSONArray jAry = json.getJSONArray("http://10.0.2.2:8080/getuser",params);
return jAry;
}
#Override
protected void onPostExecute(JSONArray json) {
for(int i = 0; i < json.length(); i++){
JSONObject c = null;
try {
c = json.getJSONObject(i);
String name = c.getString("name");
String mobno = c.getString("mobno");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
map.put("mobno", mobno);
users.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
ListAdapter adapter = new SimpleAdapter(getActivity(), users,
R.layout.user_list_single,
new String[] { "name","mobno" }, new int[] {
R.id.name, R.id.mobno});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Bundle args = new Bundle();
args.putString("mobno", users.get(position).get("mobno"));
Intent chat = new Intent(getActivity(), ChatActivity.class);
chat.putExtra("INFO", args);
startActivity(chat);
}
});
}
}
private class Logout extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... args) {
JSONParser json = new JSONParser();
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2:8080/logout",params);
return jObj;
}
#Override
protected void onPostExecute(JSONObject json) {
String res = null;
try {
res = json.getString("response");
Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();
if(res.equals("Removed Sucessfully")) {
Fragment reg = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, reg);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
SharedPreferences.Editor edit = prefs.edit();
edit.putString("REG_FROM", "");
edit.commit();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
ChatActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ChatActivity extends Activity {
SharedPreferences prefs;
List<NameValuePair> params;
EditText chat_msg;
Button send_btn;
Bundle bundle;
TableLayout tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
tab = (TableLayout)findViewById(R.id.tab);
prefs = getSharedPreferences("Chat", 0);
bundle = getIntent().getBundleExtra("INFO");
SharedPreferences.Editor edit = prefs.edit();
edit.putString("CURRENT_ACTIVE", bundle.getString("mobno"));
edit.commit();
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if(bundle.getString("name") != null){
TableRow tr1 = new TableRow(getApplicationContext());
tr1.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml("<b>"+bundle.getString("name")+" : </b>"+bundle.getString("msg")));
tr1.addView(textview);
tab.addView(tr1);
}
chat_msg = (EditText)findViewById(R.id.chat_msg);
send_btn = (Button)findViewById(R.id.sendbtn);
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TableRow tr2 = new TableRow(getApplicationContext());
tr2.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#A901DB"));
textview.setText(Html.fromHtml("<b>You : </b>" + chat_msg.getText().toString()));
tr2.addView(textview);
tab.addView(tr2);
new Send().execute();
}
});
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str = intent.getStringExtra("msg");
String str1 = intent.getStringExtra("fromname");
String str2 = intent.getStringExtra("fromu");
if(str2.equals(bundle.getString("mobno"))){
TableRow tr1 = new TableRow(getApplicationContext());
tr1.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml("<b>"+str1+" : </b>"+str));
tr1.addView(textview);
tab.addView(tr1);
}
}
};
private class Send extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... args) {
JSONParser json = new JSONParser();
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("from", prefs.getString("REG_FROM","")));
params.add(new BasicNameValuePair("fromn", prefs.getString("FROM_NAME","")));
params.add(new BasicNameValuePair("to", bundle.getString("mobno")));
params.add((new BasicNameValuePair("msg",chat_msg.getText().toString())));
JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2:8080/send",params);
return jObj;
}
#Override
protected void onPostExecute(JSONObject json) {
chat_msg.setText("");
String res = null;
try {
res = json.getString("response");
if(res.equals("Failure")){
Toast.makeText(getApplicationContext(),"The user has logged out. You cant send message anymore !",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Please can someone help me?
This:
java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.example.ibm_admin.chat.UserFragment$Load.onPostExecute(UserFragment.java:84)
means, that in file UserFragment.java at line 84 in inner class Load of class com.example.ibm_admin.chat.UserFragment there is method length was called on some object, which is null.
I suppose, that is this line:
for(int i = 0; i < json.length(); i++){
in this method parameter json equals null.
Probably, in your doInBackroung method, jObj.getJSONArray returns null.
It is hard to know what exactly happened, because your JSONParser.getJSONArray suppresses all the exceptions and returns null, if any.
Look at next two lines of logcat:
07-01 22:50:39.367 30016-30032/com.example.ibm_admin.chat E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
07-01 22:50:39.367 30016-30032/com.example.ibm_admin.chat E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
That's means somewhere inside that block in getJSONArray you have a null reference, that probably comes from topmost part of getJSONArray where other exceptions was suppressed, and is variable become null.
You have to carefully debug through all the code.
This is the exception you are getting mainly
java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.example.ibm_admin.chat.UserFragment$Load.onPostExecute(UserFragment.java:84)
To check the array is empty or not this is better before parsing.Like this
JSONArray dataArray = new JSONArray(data);
if(!(dataArray.length() == 0)){
for(int i = 0 ;i < dataArray.length();i++){
JSONObject chainObj = dataArray.getJSONObject(i);
String chain_name = chainObj.getString("chain_name");
String chain_id = chainObj.getString("retailerid");
String chain_location = chainObj.getString("area");
}
}
this is retrun null
JSONArray jAry = json.getJSONArray("http://10.0.2.2:8080/getuser",params);
in userFragment due to server response is not valid json and
when you are call json.length(). json object is null UserFragment$Load.onPostExecute(Jsonarray json).

Error org.json.JSONException

I am creating an application for Android. It is the task of retrieving data from an external database server mysql.
Everything was fine, but by the time of compilation. Gave me the error:
Errororg.json.JSONException: Value
A link to a database using php script:
$host="localhost";
$username="root";
$password="password";
$db_name="baza";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from zastep";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['zastep'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
The script is working correctly, the error shows up when compiling apk.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends Activity{
private String jsonResult;
private String url = "http://192.168.2.100/tyr/conn.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//uzyskiwanie dostępu do sieci
private class JsonReadTask extends AsyncTask<String,Void, String> {
#Override
protected String doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try
{
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is)
{
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine())!= null)
{
answer.append(rLine);
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result)
{
ListDrwaer();
}
}
public void accessWebService()
{
JsonReadTask task = new JsonReadTask();
task.execute(new String[] {url});
}
public void ListDrwaer()
{
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try
{
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("zastep");
for (int i = 0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("klasa");
String data = jsonChildNode.optString("data");
String outPut = name + "-" + data;
employeeList.add(createEmployee("employees", outPut));
}
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,android.R.layout.simple_list_item_1, new String[]{"employees"}, new int[] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String data)
{
HashMap<String, String> employeeNameNo = new HashMap<String,String>();
employeeNameNo.put(name, data);
return employeeNameNo;
}
}
Logcat:
03-11 17:26:07.790 26957-26957/pl.saperdak1gmail.rrt E/﹕ appName=pl.saperdak1gmail.rrt, acAppName=/system/bin/surfaceflinger
03-11 17:26:07.790 26957-26957/pl.saperdak1gmail.rrt E/﹕ 0
please help

Categories

Resources