I am accessing an external database(000webhost) for fetching the email address in the app and printing them into a ListView. I am getting the correct response from the server which is printing in the logcat, but I am getting a null pointer exception.
This is what my logcat looks like:
05-11 16:00:39.891 24149-24914/info.androidhive.loginandregistration E/Entity Response:﹕ {"email":[{"email":"adeel#gmail.com"},{"email":"yamini#gmail.com"},{"email":"mona#gmail.com"}]}{"tag":"DisplayFriends","error":true,"error_msg":"Unknown 'tag' value. It should be either 'login' or 'register'"}
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
05-11 16:00:39.895 24149-24149/info.androidhive.loginandregistration D/AndroidRuntime﹕ Shutting down VM
05-11 16:00:39.898 24149-24149/info.androidhive.loginandregistration E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.loginandregistration, PID: 24149
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at info.androidhive.loginandregistration.FriendsList.setListAdapter(FriendsList.java:55)
at info.androidhive.loginandregistration.FriendsList$GetAllCustomerTask.onPostExecute(FriendsList.java:74)
at info.androidhive.loginandregistration.FriendsList$GetAllCustomerTask.onPostExecute(FriendsList.java:60)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Following are my java files:
ApiConnector.java
public class ApiConnector {
Global g=Global.getInstance();
String a=g.getLogInEmail();
String b="DisplayFriends";
public JSONArray GetAllCustomers()
{
// URL for getting all customers
// String url = "http://z.locationtest.comxa.com/index.php?tag=DisplayFriends&loggedInEmail="+a;
String url = "http://z.locationtest.comxa.com/index.php";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
HttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpPost httpPost = new HttpPost(url);
try
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", b));
params.add(new BasicNameValuePair("loggedInEmail", a));
httpPost.setEntity(new UrlEncodedFormEntity(params));
// HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray=null;
JSONObject jsonObject =null;
if (httpEntity != null)
{
try
{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response: ", entityResponse);
jsonObject = new JSONObject(entityResponse);
jsonArray = jsonObject.getJSONArray("email");
// jsonArray = new JSONArray(entityResponse);
/*for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
Log.d("TAG_LOCATIONS", jsonArray.toString(i));
}*/
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return jsonArray;
}
}
FriendList.java
public class FriendsList extends Activity {
private ListView listViewFriends;
private JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.listViewFriends=(ListView)this.findViewById(R.id.listViewFriends);
new GetAllCustomerTask().execute(new ApiConnector());
}
void setListAdapter(JSONArray jsonArray)
{
//this.jsonArray=jsonArray;
this.listViewFriends.setAdapter(new GetAllFriendsListViewAdapter(jsonArray,this));
}
private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
#Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllCustomers();
}
#Override
protected void onPostExecute(JSONArray jsonArray)
{
setListAdapter(jsonArray);
}
}
}
GetAllFriendsListViewAdapter.java
public class GetAllFriendsListViewAdapter extends BaseAdapter
{
private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater= null;
public GetAllFriendsListViewAdapter(JSONArray jsonArray, Activity a)
{
this.activity=a;
this.dataArray=jsonArray;
inflater= (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return this.dataArray.length();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ListCell cell;
if(convertView==null)
{
convertView=inflater.inflate(R.layout.item_layout,null);
cell=new ListCell();
cell.email=(TextView)convertView.findViewById(R.id.textViewFriends);
convertView.setTag(cell);
}
else
{
cell=(ListCell)convertView.getTag();
}
try
{
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.email.setText(" "+jsonObject.getString("email"));
}
catch(JSONException e)
{
e.printStackTrace();
}
return convertView;
}
private class ListCell
{
private TextView email;
}
}
I am new to Android. It would be great if someone help me find the error in my code.
A NullPointerException is thrown at runtime whenever your program
attempts to use a null as if it was a real reference.
So the error is not in getting the data from wherever you are hosting it. It is because you are trying to use a variable which is null.
You have done this private JSONArray jsonArray; but you need to do this too variable = new variable-type(); to allocate memory too. Please check the part above and do some googling. There is no error in getting the data, it is happening when you try to do something with it.
You are just declaring variables as below
private ListView listViewFriends;
private JSONArray jsonArray;
But this is not enough.
You need to define them in your code too.
Related
I am a newer android developer , and i try to make an app which depend on MySQL.
so i have MySQL database and I have A php that return its data in Json format at this link here.
so i make a simple app that take this data and show it in list view by AsyncTask & Service Handler .
Note 1: I try this app with another database [Not Free Domain/website] and it work But with my database didn't work [free hosting]
Note 2: I try to comment the "Try & Catch" code at doInBackground method at AsyncTask class & make a dummy data manually So the app works !!, so what???!!
Update: i used the emulator and i got some red massages that i do not understand what its mean so i take it as screen shot
My php code:
<?php
$dbname = 'zoubg_18363398_center';
$dbserver = 'sql104.kariya-host.com';
$dbusername = 'zoubg_18363398';
$dbpassword = '28721235';
$dbconnect = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);
$getpostssql = "SELECT * FROM users";
$posts = $dbconnect->query($getpostssql);
$postsarray = array();
while($row = mysqli_fetch_array($posts, MYSQL_ASSOC)){
$temp['id'] = $row['id'];
$temp['name'] = $row['name'];
$temp['password'] = $row['password'];
$temp['email'] = $row['email'];
$temp['adress'] = $row['adress'];
array_push($postsarray, $temp);
}
echo json_encode(array("posts"=>$postsarray), JSON_UNESCAPED_UNICODE);
</blink>
My java code
public class MoveActivity extends AppCompatActivity {
ListView LVMove;
MoveAdapter moveAdapter;
ArrayList<MoveInfo> MoveList = new ArrayList<>();
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move);
LVMove = (ListView) findViewById(R.id.lv_test);
// dummy data manually
/*
MoveInfo Move1 = new MoveInfo();
Move1.setId(1);
Move1.setSName("Ahmed");
Move1.setSPass("123456");
Move1.setSEmail("Ahmed#asdf.com");
Move1.setSAddress("CairoEgypt");
MoveList.add(Move1);
MoveInfo Move2 = new MoveInfo();
Move2.setId(2);
Move2.setSName("Ali");
Move2.setSPass("456789");
Move2.setSEmail("Ali#asdf.com");
Move2.setSAddress("AlexEgypt");
*/
new GetMoves().execute("http://centertest.kariya-host.com/testjjjsn.php");
}
class GetMoves extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MoveActivity.this);
pDialog.setMessage(" Please wait ... ");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... strings) {
String url = strings[0];
ServiceHandler serviceHandler = new ServiceHandler();
JSONObject jsonObject = serviceHandler.makeServiceCall(url, ServiceHandler.GET);
try {
JSONArray DATA = jsonObject.getJSONArray("posts");
for (int i = 0; i < DATA.length(); i++) {
JSONObject item = DATA.getJSONObject(i);
MoveInfo Move = new MoveInfo();
int id = item.getInt("id");
String name = item.getString("name");
String password = item.getString("password");
String email = item.getString("email");
String adress = item.getString("adress");
Move.setId(id);
Move.setSName(name);
Move.setSPass(password);
Move.setSEmail(email);
Move.setSAddress(adress);
MoveList.add(Move);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(pDialog.isShowing()){
pDialog.dismiss();
moveAdapter = new MoveAdapter(MoveList, getApplicationContext());
LVMove.setAdapter(moveAdapter);
}
}
}
}
ServiceHandler Code
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public JSONObject makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public JSONObject makeServiceCall(String url, int method,
List<NameValuePair> params) {
JSONObject jsonObject=null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
jsonObject=new JSONObject(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
MoveAdapter code
public class MoveAdapter extends BaseAdapter {
ArrayList<MoveInfo> MoveList;
Context context;
LayoutInflater inflater ;
public MoveAdapter (ArrayList<MoveInfo> MoveList, Context context){
this.MoveList = MoveList;
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return MoveList.size();
}
#Override
public Object getItem(int i) {
return MoveList.get(i);
}
#Override
public long getItemId(int i) {
return MoveList.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.item_list, null);
}
TextView TvIds = (TextView) view.findViewById(R.id.tv_Ids);
TextView TvNames = (TextView) view.findViewById(R.id.tv_Names);
TextView TvPasss = (TextView) view.findViewById(R.id.tv_Passs);
TextView TvEmails = (TextView) view.findViewById(R.id.tv_emails);
TextView TvAddresss = (TextView) view.findViewById(R.id.tv_addresss);
TvIds.setText(MoveList.get(i).getId()+"");
TvNames.setText(MoveList.get(i).getSName());
TvPasss.setText(MoveList.get(i).getSPass());
TvEmails.setText(MoveList.get(i).getSEmail());
TvAddresss.setText(MoveList.get(i).getSAddress());
return view;
}
}
update: every thing was right, problem was in hosting server when i change hosting server , every thing work probably Thanks for interresting
I want to read and store all JSON values from this api Link with get request "Mini" as example (which is actually an user input variable) and the last number is the page your are viewing. Every page can hold a max of 50 results. The same link is also in XML format (I must read and store as JSON, this is for easier understanding)
In this exmaple there are 8 pages with a total of 359 results. I need to loop through all pages and add all the JSON values to the same object list.
I have the code which work to read one page. I do not know how to make it loop through all pages and add to same object list.
In the acitivty.java onCreate I call the AsyncTask.
String userSearchRequest = search_activity_data.getString("userSearchRequest");
int page = 0;
String spidy_iTN_url = "http://www.gw2spidy.com/api/v0.9/json/item-search/" + userSearchRequest + "/" + page;
itemsByInput_AsyncTask itemsByInput_AsyncTask = new itemsByInput_AsyncTask();
itemsByInput_AsyncTask.setItemListToListings(this);
itemsByInput_AsyncTask.execute(spidy_iTN_url);
This is my AsyncTask class called itemsByInput_AsyncTask.java
import constructors.itemResults_api_constr;
import constructors.itemRoot_api_constr;
public class itemsByInput_AsyncTask extends AsyncTask<String, Void, JSONObject> {
JSONObject Jo_result;
private itemListToListings itemListToListings;
public void setItemListToListings (itemListToListings itemListToListings) {
this.itemListToListings = itemListToListings;
}
#Override
protected JSONObject doInBackground(String... params) {
return spidyHttpGetRequest(params[0]);
}
public JSONObject spidyHttpGetRequest(String URL){
try {
HttpGet get = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Jo_result = new JSONObject(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return Jo_result;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
this.itemListToListings.itemListToListings(JoToJO_constructor(jsonObject));
}
public itemRoot_api_constr JoToJO_constructor(JSONObject Jo_result) {
itemRoot_api_constr spidy_iTN_rootO = new itemRoot_api_constr();
try {
spidy_iTN_rootO.setCount(Jo_result.getInt("count"));
spidy_iTN_rootO.setPage(Jo_result.getInt("page"));
spidy_iTN_rootO.setLast_page(Jo_result.getInt("last_page"));
spidy_iTN_rootO.setTotal(Jo_result.getInt("total"));
JSONArray list = new JSONArray(Jo_result.getString("results"));
for (int i = 0; i < spidy_iTN_rootO.getCount(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
itemResults_api_constr spidy_iTN_resultsO = new itemResults_api_constr();
spidy_iTN_resultsO.setData_id(resultsObject
.getInt("data_id"));
spidy_iTN_resultsO.setName(resultsObject
.getString("name"));
spidy_iTN_resultsO.setRarity(resultsObject
.getInt("rarity"));
spidy_iTN_resultsO.setRestriction_level(resultsObject
.getInt("restriction_level"));
spidy_iTN_resultsO.setImg(resultsObject
.getString("img"));
spidy_iTN_resultsO.setType_id(resultsObject
.getInt("type_id"));
spidy_iTN_resultsO.setSub_type_id(resultsObject
.getInt("sub_type_id"));
spidy_iTN_resultsO.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
spidy_iTN_resultsO.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
spidy_iTN_resultsO.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
spidy_iTN_resultsO.setOffer_availability(resultsObject
.getInt("offer_availability"));
spidy_iTN_resultsO.setSale_availability(resultsObject
.getInt("sale_availability"));
spidy_iTN_resultsO.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
spidy_iTN_resultsO.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
spidy_iTN_rootO.addObject(spidy_iTN_resultsO);
}
} catch (JSONException e) {
e.printStackTrace();
}
return spidy_iTN_rootO;
}
public interface itemListToListings {
public void itemListToListings(itemRoot_api_constr resultClass);
}
}
And finally in my activity.java i can use my object in the method itemListToListings().
How can I make this loop through all pages (last_page property) and add all JSON values as object in the same list.
EDIT: My itemListToListings function in my activity.
public void itemListToListings(final itemRoot_api_constr spidy_iTN_construct) {
ArrayList<listItemWidgets_constr> image_details = getListData(spidy_iTN_construct);
final ListView lv1 = (ListView) findViewById(R.id.listView);
lv1.setAdapter(new itemListAdapter(this, image_details));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
//listItemWidgets_constr newsData = (listItemWidgets_constr) lv1.getItemAtPosition(position);
Toast.makeText(resultsActivity.this, "Selected :" + spidy_iTN_construct.results(position).name, Toast.LENGTH_LONG).show();
Intent i = new Intent(resultsActivity.this, listingsActivity.class);
i.putExtra("itemId", spidy_iTN_construct.results(position).data_id);
startActivity(i);
}
});
}
EDIT 3: error log
05-01 07:17:39.828 3620-3620/com.example.krijn.gw2TP_androidMobile E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.krijn.gw2TP_androidMobile, PID: 3620
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.krijn.gw2TP_androidMobile.AsyncTasks.itemsByInput_AsyncTask$itemListToListings.itemListToListings(com.example.krijn.gw2TP_androidMobile.constructors.itemRoot_api_constr)' on a null object reference
at com.example.krijn.gw2TP_androidMobile.AsyncTasks.itemsByInput_AsyncTask.onProgressUpdate(itemsByInput_AsyncTask.java:88)
at com.example.krijn.gw2TP_androidMobile.AsyncTasks.itemsByInput_AsyncTask.onProgressUpdate(itemsByInput_AsyncTask.java:27)
After I get this error in the Logcat I still see the Log updating with the following in doInBackground
for (int n = 1; n < nPage; n++){
Log.i("gw2Log", "n: " + n);
publishProgress(JoToJO_constructor(spidyHttpGetRequest(makeUrl(n))));
}
After that is done looping the application crashes.
I think you want to make chain calls depending on last_page property you get from the first page. I would do somethig like this where upon each completion of a request the UI is updated on onProgressUpdate
public class itemsByInput_AsyncTask extends AsyncTask<Void, itemRoot_api_constr, Void> {
JSONObject Jo_result;
private itemListToListings itemListToListings;
String userSearchRequest;
public itemsByInput_AsyncTask(String userSearchRequest){
this.userSearchRequest = userSearchRequest;
}
private String makeUrl(int page){
return "http://www.gw2spidy.com/api/v0.9/json/item-search/" +
this.userSearchRequest + "/" + page;
}
#Override
protected Void doInBackground(Void... params) {
itemRoot_api_constr iac;
iac = JoToJO_constructor(spidyHttpGetRequest(makeUrl(0)));
nPage = iac.getLast_page();
publishProgress(iac);
for (int n = 1; n<nPage; n++){
publishProgress(spidyHttpGetRequest(makeUrl(n)));
}
return null;
}
#Override
protected void onProgressUpdate(itemRoot_api_constr... iacs) {
super.onProgressUpdate(iacs);
// assuming method itemListToListings updates UI
// if it doesn't then publishProgress and onProgressUpdate are not needed
// and itemListToListings can be done in doInBackground
this.itemListToListings.itemListToListings(iacs[0]);
}
#Override
protected Void onPostExecute(Void void) {
super.onPostExecute(void);
// unused
}
}
Also:
Adapter, views, and related click listeners should be initiated once. You should move all variables inside of itemListToListings as your Activity field so everytime this callback is called, they won't need to be initiated again.
ListView lv1;
ArrayList<listItemWidgets_constr> image_details = new ArrayList<>();
itemListAdapter adapter;
void onCreate(){
...
lv1 = (ListView) findViewById(R.id.listView);
adapter = new itemListAdapter(this, image_details);
lv1.setOnItemClickListener(...);
}
public void itemListToListings(final itemRoot_api_constr spidy_iTN_construct) {
image_details.clear();
image_details.addAll(getListData(spidy_iTN_construct));
adapter.notifyDataSetChanged();
}
I know there are a lot of questions asked like this but I've looked at them all and none of the answers have worked for me.
Here is my java class
public class AllBugsActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> bugsList;
private static String url_all_bugs = "http://10.0.2.2/FinalYearProject/FYPFinal/android_connect/get_all_bugs.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_BUGS = "bugs";
private static final String TAG_BID = "bid";
private static final String TAG_NAME = "name";
JSONArray bugs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_bugs);
bugsList = new ArrayList<HashMap<String, String>>();
new LoadAllBugs().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bid = ((TextView) view.findViewById(R.id.bid)).getText()
.toString();
Intent in = new Intent(getApplicationContext(),
EditBugActivity.class);
in.putExtra(TAG_BID, bid);
startActivityForResult(in, 100);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllBugs extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllBugsActivity.this);
pDialog.setMessage("Loading bugs. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_bugs, "GET", params);
Log.d("All Bugs: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
bugs = json.getJSONArray(TAG_BUGS);
for (int i = 0; i < bugs.length(); i++) {
JSONObject c = bugs.getJSONObject(i);
String id = c.getString(TAG_BID);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_BID, id);
map.put(TAG_NAME, name);
bugsList.add(map);
}
} else {
Intent i = new Intent(getApplicationContext(),
NewBugActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
AllBugsActivity.this, bugsList,
R.layout.list_bug, new String[] { TAG_BID,
TAG_NAME},
new int[] { R.id.bid, R.id.name });
setListAdapter(adapter);
}
});
}
}
}
Heres my JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
Heres the error im getting
03-21 17:06:15.158 1266-1280/com.example.neil.fypy4 E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:98)
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
03-21 17:06:15.511 1266-1266/com.example.neil.fypy4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-21 17:06:16.008 1266-1266/com.example.neil.fypy4 E/WindowManager﹕ Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41cd1748 that was originally added here
android.view.WindowLeaked: Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41cd1748 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.onPreExecute(AllBugsActivity.java:92)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.example.neil.fypy4.AllBugsActivity.onCreate(AllBugsActivity.java:50)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
My php class
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM bugs") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["bugs"] = array();
while ($row = mysql_fetch_array($result)) {
$bug = array();
$bug["bid"] = $row["bid"];
$bug["name"] = $row["name"];
$bug["severity"] = $row["severity"];
$bug["description"] = $row["description"];
$bug["created_at"] = $row["created_at"];
$bug["updated_at"] = $row["updated_at"];
array_push($response["bugs"], $bug);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No bugs found";
echo json_encode($response);
}
?>
Any help would be greatly appreciated.
So in your stack trace, it'll show you line numbers: from this you can triangulate in your code where the NPE is coming from. Since you don't provide line numbers here, I'm going to take a guess that int success = json.getInt(TAG_SUCCESS); is causing the NPE. The reason is that it's the first possibly null object in doInBackground(...)--if you look at the JSONParser class, you return jObj which is a field member that is initialized to null, and only set if an error did not occur. That is, you do not check in doInBackground(...) whether JSONObject json returns null or not from = jParser.makeHttpRequest(url_all_bugs, "GET", params); instead relying on the TAG_SUCCESS. But this is a chicken and egg problem, since if it fails it can be null and there is no tag to check for success!
Anyways, my advice is to add if (json != null) before the try/catch in doInBackground(...). You'll probably find your JSONParser class is failing to parse correctly. You can use the line numbers from the stack trace to pinpoint where the problem is coming from, or just use the debugger and step through your code execution.
On a side note, you can make public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) a static method since the variables
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
don't need to be class scoped (and they are already static!). Just make them method scope and have a convenient static method call to parse your json.
A final comment: you don't need to call runOnUiThread(...) from onPostExecute(...) because onPostExecute(...) runs on the UI thread for every Async task. That's simply how Async task works.
While Running the code (given after the error msg) throws the error as
Coding follows:
public class Slide extends ActionBarActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> detailsList; //Creating a Arraylist
private static String URL = "URL to my php page";
private static final String TAG_DETAILS = "details";
private static final String TAG_TITLE = "title";
JSONArray details = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide);
new onlineload().execute();
}
class onlineload extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Slide.this);
pDialog.setMessage("Fetching Books...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String title = "";
TextView tvTitle = (TextView)findViewById(R.id.Title);
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
Log.d("All Products:",json.toString());
try {
details = json.getJSONArray(TAG_DETAILS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
title = title + c.getString(TAG_TITLE)+"\n";
tvTitle.setText(title);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Shown above is my java code..
Function of this code is to fetch Book title (more than 10 books title is available in database)from the online database and view it in an scroll view activity ..
my php code is working am getting the output only the problem is in displaying it in android activity !!
Looking for some help!!
JSON CODE:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONArray makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
Log.d("Entered Get", "Get SUccess"+url+method);
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Agree with #ρяσѕρєя K
There was cast exception occurred that means you need to use JSON Array. Coz you are using JSON Object where actually JSON Array is required.
If you are confused within response which is receiving is JSONArray or JSONObject then you can go for get() method which return data in Object manner.
example : Object c = details.get(i);
So after that you can check for
If(c instanceOf JSONArray){
/// perform as array operation
}
If(c instanceOf JSONObject){
// perform json object retrieving operation
}
I am trying to run an app based on WorlBank API. I have a JSON URL to get data about a country and then show it in TextViews. Simple. But as soon as I run the app in closes.
Here are my files:
Main Activity:
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON node Names
private static final String PAGE = "page";
private static final String VALUE = "value";
private static final String NAME = "name";
private static final String GEO = "region";
JSONArray page = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
//Getting JSON Array
page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
//Sorting JSON item in a Variable
String value = c.getString(VALUE);
String name = c.getString(NAME);
String geo = c.getString(GEO);
//Importing to TextView
final TextView id1 = (TextView) findViewById(R.id.id);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView geo1 = (TextView) findViewById(R.id.geo);
//set JSON Data in TextView
id1.setText(value);
name1.setText(name);
geo1.setText(geo);
} catch (JSONException e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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;
}
}
XML:
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/id"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/geo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/id"
android:layout_alignParentTop="true"
android:layout_marginTop="76dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
Any idea?
world bank api: http://data.worldbank.org/node/18
UPDATE:
android:minSdkVersion="8"
android:targetSdkVersion="18"
FATAL EXCEPTION: main
E/AndroidRuntime(966): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonsyctask/com.example.jsonsyctask.Main}: android.os.NetworkOnMainThreadException
E/AndroidRuntime(966): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(966): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(966): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(966): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime(966): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(966): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(966): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(966): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(966): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(966): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
The problem is happening because you are trying to perform network operations on the UI thread. You need to use a background thread for network operations.
Use an AsyncTask as follows:
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON node Names
private static final String PAGE = "page";
private static final String VALUE = "value";
private static final String NAME = "name";
private static final String GEO = "region";
JSONArray page = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetJSONTask().execute(url);
// do not parse here..
...
...
}
...
...
class GetJSONTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
try {
JSONParser jParser = new JSONParser();
return jParser.getJSONFromUrl(urls[0]);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(JSONObject json) {
// do all the parsing here:
try {
//Getting JSON Array
page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
//Sorting JSON item in a Variable
String value = c.getString(VALUE);
String name = c.getString(NAME);
String geo = c.getString(GEO);
//Importing to TextView
final TextView id1 = (TextView) findViewById(R.id.id);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView geo1 = (TextView) findViewById(R.id.geo);
//set JSON Data in TextView
id1.setText(value);
name1.setText(name);
geo1.setText(geo);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
Ref: http://developer.android.com/reference/android/os/AsyncTask.html
update another bug spotted, update XML
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
...
...
You cannot have two views and say A below B, then B below A that will cause problems!
You can greatly simplify everything you are doing using droidQuery:
$.ajax(new AjaxOptions().url(url).success(new Function() {
#Override
public void invoke($ d, Object... args) {
JSONObject json = (JSONObject) args[0];
JSONArray page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
$.with(MyActivity.this, R.id.id).text(c.getString(VALUE))
.id(R.id.name).text(c.getString(NAME))
.id(geo).text(c.getString(GEO));
}
}));
I used Kevin Sawicki's HTTP Request Library which is very helpful, find the working example bellow. Don't forget to add android permission
<uses-permission android:name="android.permission.INTERNET" />
Retrieved json value from http://api.worldbank.org/countries/ir?format=json
package com.javasrilankansupport.testhttps;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadTask().execute("http://api.worldbank.org/countries/ir?format=json");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadTask extends AsyncTask<String, Long, Boolean> {
protected Boolean doInBackground(String... urls) {
try {
// kevinsawicki's HttpRequest from github
HttpRequest request = HttpRequest.get(urls[0])
.trustAllCerts() // for HTTPS request
.trustAllHosts() // to trust all hosts
.acceptJson(); // to accept JSON objects
if (request.ok()) {
JSONObject jsonObject;
try {
String s = request.body();
Log.d("MyApp",
"Downloaded json data: "+ s);
// change parameters according to your JSON
jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject
.getJSONArray("categories");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
Log.d("MyApp",
"Downloaded json data: "
+ jsonObj.getString("id") + " "
+ jsonObj.getString("slug"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
System.out.print("error");
}
} catch (HttpRequestException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onProgressUpdate(Long... progress) {
// progress bar here
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
}
}
Getting data from server require following steps :
make sure your generated json string is in correct format.You can find it on various site.
while requesting from server you must use AsyncTask.
Following example can be helpful to understand the logic
package com.example.sonasys.net;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.sonaprintersd.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
public class SingleContactActivity extends Activity {
private static final String TAG_CONTACTS = "Contacts";
private static final String TAG_POSTLINE = "PostLine";
private static final String TAG_Post_Img = "Post_Img";
private static final String TAG_Post_Img_O = "Post_Img_O";
private static String url;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
Bitmap bitmap;
ImageView image;
String imagepath2;
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url = "http://test2.sonasys.net/MobileApp/GetSinglePost?UserId="
+ uid.getText() + "&Post_ID=" + pid.getText();
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
// pDialog.setTitle("Post Details");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
JSONObject c = contacts.getJSONObject(0);
details = c.getString(TAG_POSTLINE);
imagepath = c.getString(TAG_Post_Img);
imagepath2 = c.getString(TAG_Post_Img_O);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**/
TextView Details = (TextView) findViewById(R.id.details);
// Details.setText(details);
Details.setText(android.text.Html.fromHtml(details));
}
}
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
My guess is that this is because you're attempting network activity on the main thread. That's a no-no.
Perhaps adding a default exception handler and a breakpoint there will help-
Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
throwable.printStackTrace();
}
});