Anyone knows how to transfer data from async task? - java

I tried more and more and nothing is worked.Last i used sharedPreferences.but that not relevant to me...Please help me to replace the sharedPreferences..
my MainActivity is
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.CancellationSignal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView textView,textView2;
String[] name=new String[100];
String[] id=new String[100];
String[] names=null;
String[] idg=new String[100];
String[] ids=null;
int i;
int len;
ArrayList<NewsItem> listData;
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Fetch().execute();
SharedPreferences sharedPreferences = getSharedPreferences("local", 0);
SharedPreferences.Editor editor=sharedPreferences.edit();
size = sharedPreferences.getInt("array_size", 0);
ids = new String[size];
names = new String[size];
for(i=0; i<size; i++){
ids[i]=sharedPreferences.getString("array1_" + i, null);
names[i]=sharedPreferences.getString("array2_" + i, null);
}
editor.clear();
editor.commit();
listData = getListData();
final ListView listView = (ListView) findViewById(R.id.custom_list);
listView.setAdapter(new CustomListAdapter(this, listData));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
NewsItem newsData = (NewsItem) listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
}
});
//textView=(TextView)findViewById(R.id.textView);
//textView2=(TextView)findViewById(R.id.textView2);
}
class Fetch extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.cancel();
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://andrinfo.comli.com/rimgid.php";
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
len = Jarray.length();
for(i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
id[i] ="http://developer.andrinfo.comli.com/img/"+ Jasonobject.getInt("id")+".jpg";
name[i] = Jasonobject.getString("name");
SharedPreferences sharedPreferences=getSharedPreferences("local",0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("array_size", len);
for(int i=0;i<len; i++) {
editor.putString("array1_" + i, id[i]);
editor.putString("array2_" + i, name[i]);
}
editor.apply();
drac d=new drac();
//d.exe(id,name,len);
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
private ArrayList<NewsItem> getListData() {
ArrayList<NewsItem> listMockData = new ArrayList<NewsItem>();
String[] images = getResources().getStringArray(R.array.images_array);
String[] headlines = getResources().getStringArray(R.array.headline_array);
for (i = 0; i < size; i++) {
NewsItem newsData = new NewsItem();
newsData.setUrl(ids[i]);
newsData.setHeadline(names[i]);
newsData.setReporterName("Price");
newsData.setDate("May 26, 2015, 1:35PM");
listMockData.add(newsData);
}
return listMockData;
}
class drac{
public void exe(String[] ids, String[] idg,int size)
{
for (i = 0; i < size; i++) {
Toast.makeText(getApplicationContext(), ""+ids[i], Toast.LENGTH_SHORT).show();
}}}
}
And the PROBLEM IS IN MainActivity.java

See http://developer.android.com/intl/es/reference/android/os/AsyncTask.html. Especially the part with the result.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Finally I solved by using volley library thanks for the response.

Related

Android: How to retrieve a single data from a web server and display it to a textview?

i want to display an employee last clock-in from a web server. The problem is i'm not really sure how to retrieve a single last clock-in and display it to a textview. Here is my code, JSONParser.java:
package com.example.win7.simpleloginapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
int timeout=10000; //in milisecond = 10 detik
// constructor
public JSONParser() {
//timeout = new Values().gettimeout();
}
// 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 {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
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(httpParameters);
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 (SocketException ste)
{
Log.e("Timeout Exception: ", ste.toString());
}
catch (ConnectTimeoutException e)
{
Log.e("Timeout Exception: ", e.toString());
}
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;
}
}
ServerRequest.java:
package com.example.win7.simpleloginapp;
import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.io.HttpRequestParser;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class ServerRequest {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = ".................net";
final static String TAG_USER = "user";
private Context mContext;
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String NameStr = "Name";
JSONArray user;
JSONParser jsonParser = new JSONParser();
public ServerRequest(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing..");
progressDialog.setMessage("Please Wait....");
mContext = context;
}
public void storeUserDataInBackground(user user, GetUserCallback userCallback) {
progressDialog.show();
new StoreUserDataAsyncTask(user, userCallback).execute();
}
public void fetchUserDataInBackground(user user, GetUserCallback callBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user, callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
user user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("http://.........................../register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public class fetchUserDataAsyncTask extends AsyncTask< Void, Void, user> {
user user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected user doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("................................../fetchUserData.php");
user returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length()==0)
{
returnedUser = null;
}
else
{
String Name1 = jObject.getString("Name");
//String Name1 = "ekin";
storeData(Name1);
//Name1 = "hello";
returnedUser = new user(user.username, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(user returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
public SharedPreferences getSharedPref(){
return mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
}
public void storeData(String Name1) {
getSharedPref().edit().putString("data", Name1).apply();
}
public String getData(){
return getSharedPref().getString("data", "");
}
}
And here is the MainActivity.java:
package com.example.win7.simpleloginapp;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import android.app.AlertDialog;
import android.location.LocationListener;
import com.example.win7.simpleloginapp.model.JSONParser2;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button button_logout;
TextView etUsername , etName, lastTimeDisp, lastDateDisp; //baru
UserLocalStore userLocalStore;
Button clockIN1, clockOUT1;
Date date = new Date();
String AndroidId;
String username;
double longitude;
double latitude;
private TextView locationText;
private TextView addressText;
private GoogleMap map;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
JSONArray user = null;
JSONParser jsonParser = new JSONParser();
public static final String TAG_SUCCESS = "success";
public static final String TAG_USER = "user";
public static final String TAG_STAFF_ID = "staffID";
public static final String TAG_DATE = "date";
public static final String TAG_TIME = "time";
public static final String TAG_LONG = "longitude";
public static final String TAG_LAT = "latitude";
private Button scannerButton;
private Button camButton;
String staffIDStr, dateStr, timeStr, latitudeStr, longitudeStr;
String user_name;
SharedPreferences sharedPreferences;
public static final String mypreference = "MyPrefs" ;
public static final String NameStr = "Name";
ActionBar actionbar;
TextView textview;
LayoutParams layoutparams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBarTitleGravity();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3B5999")));
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
setContentView(R.layout.activity_main);
etUsername = (TextView) findViewById(R.id.etUsername);
etName = (TextView) findViewById(R.id.etName);
lastTimeDisp = (TextView) findViewById(R.id.lastTimeDisp); //baru
lastDateDisp = (TextView) findViewById(R.id.lastDateDisp); //baru
button_logout = (Button) findViewById(R.id.bLogout);
AnalogClock ac = (AnalogClock) findViewById(R.id.analogClock1);
DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
clockIN1 = (Button) findViewById(R.id.clockIN);
clockOUT1 = (Button) findViewById(R.id.clockOUT);
etUsername.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
etName.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.apply(); //baru - tukar commit() ke apply()
ServerRequest serverRequest = new ServerRequest(getApplicationContext());
ServerRequest2 serverRequest2 = new ServerRequest2(getApplicationContext());
Log.d("", "The value is : " + serverRequest.getData());
String username1 = serverRequest.getData();
String timeL = serverRequest2.getData();
String dateL = serverRequest2.getData();
etName.setText(username1);
lastTimeDisp.setText(timeL); //baru
lastDateDisp.setText(dateL); //baru
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
replaceMapFragment();
clockIN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//date.setTime(System.currentTimeMillis()); //set to current time
clockIN1.setClickable(false);
Calendar c = Calendar.getInstance();
dateStr = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
timeStr = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE);
staffIDStr = etUsername.getText().toString();
new createClockIn().execute();
clockIN1.setEnabled(false);
clockIN1.setClickable(false);
}
});
userLocalStore = new UserLocalStore(this);
}
private void ActionBarTitleGravity() {
actionbar = getSupportActionBar();
textview = new TextView(getApplicationContext());
layoutparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutparams);
textview.setText("MysysESS");
textview.setTextColor(Color.WHITE);
textview.setGravity(Gravity.CENTER);
textview.setTextSize(25);
textview.setTypeface(Typeface.DEFAULT_BOLD);
actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(textview);
}
class createClockIn extends AsyncTask<String, String, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("LOADING.");
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_STAFF_ID, staffIDStr));
params.add(new BasicNameValuePair(TAG_DATE, dateStr));
params.add(new BasicNameValuePair(TAG_TIME, timeStr));
params.add(new BasicNameValuePair(TAG_LONG, longitudeStr));
params.add(new BasicNameValuePair(TAG_LAT, latitudeStr));
JSONObject json = jsonParser.makeHttpRequest("http://.........................../createClockIN.php", "POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
finish();
} else {
return "gagal_database";
}
} catch (JSONException e)
{
e.printStackTrace();
return "gagal_koneksi_or_exception";
}
return "sukses";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equalsIgnoreCase("gagal_database")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "There is a problem , check your connection DB!", Toast.LENGTH_SHORT).show();
} else if (result.equalsIgnoreCase("gagal_koneksi_or_exception")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "There is a problem , check your connection!", Toast.LENGTH_SHORT).show();
} else if (result.equalsIgnoreCase("sukses")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "Lets work!", Toast.LENGTH_SHORT).show();
String staffID1 = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("username", staffID1);
startActivity(intent);
}
}
}
//on start function login function
#Override
protected void onStart() {
super.onStart();
if (authenticate() == true)
displayUserDetails();
else
startActivity(new Intent(MainActivity.this, login.class));
}
private boolean authenticate() {
return userLocalStore.getUserLoggedIn();
}
private void displayUserDetails() {
user user = userLocalStore.getLoggedInUser();
etUsername.setText(user.username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
LinearLayout main_view = (LinearLayout) findViewById(R.id.main_view);
switch (item.getItemId()) {
case R.id.logout:
userLocalStore.clearUserData();
startActivity(new Intent(this, login.class));
finish();
return true;
case R.id.history:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
String username1 = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), ListHistory.class);
intent.putExtra("username", username1);
startActivity(intent);
return true;
case R.id.location:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
String username2 = etUsername.getText().toString();
Intent intent2 = new Intent(getApplicationContext(), LocationActivity.class);
intent2.putExtra("username", username2);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// super.onBackPressed(); // Comment this super call to avoid calling finish()
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
View frag = findViewById(R.id.map);
frag.setVisibility(View.INVISIBLE);
map.getUiSettings().setZoomGesturesEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
longitudeStr = Double.toString(longitude);
latitudeStr = Double.toString(latitude);
if ((longitude > 101.650000 && longitude < 101.670000 && latitude > 2.925000 && latitude < 2.927000) ||
(longitude > 101.640000 && longitude < 101.660000 && latitude > 2.900000 && latitude < 2.920000) ||
(longitude > 101.680000 && longitude < 101.700000 && latitude > 3.140000 && latitude < 3.170000) ||
(longitude > 103.620000 && longitude < 103.640000 && latitude > 1.640000 && latitude < 1.660000))
{
clockIN1.setEnabled(true);
scannerButton.setEnabled(true);
camButton.setEnabled(true);
} else {
Toast.makeText(MainActivity.this, "YOU ARE NOT IN THE OFFICE!", Toast.LENGTH_SHORT).show();
clockIN1.setEnabled(false);
scannerButton.setEnabled(false);
camButton.setEnabled(false);
}
new GetAddressTask(MainActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
}
};
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Settings your GPS",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
For your information, I have to retrieve the data from another web server url(http://........................./lastClock.php) and the name of the entity from the table is dclkrec(represent date) and cclktime(represent time).
Any help from you guys would be very appreciated. Thank you in advanced.
You are doing a lot of wheel reinvention here. There are tools for networking and serialising/deserialising data.
For networking I can recommend Retrofit
Working with JSON objects Gson
Try these and your life will be much easier. Trust me. It is worth investing a little time.

The simpleAdapter shows an error in the constructor

I am with a problem in my code . I tried many things in this code , However it does not fix . In the end the error is described. It is something related with constructor.
SelectActivityAnswer.java
package com.example.test;
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;
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 android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class SelectAnswerActivity extends Fragment {
final static String ARG_POSITION_ANSWER = "position";
private String jsonResult;
private String url = "http://myip/employee_details.php";
private ListView listView;
public SelectAnswerActivity() {
// Empty constructor required for fragment subclasses
}
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//SimpleAdapter simpleAdapter = new SimpleAdapter(this, null, 0, null, null);
View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);
accessWebService();
// selectListAns = (ListView) rootView.findViewById(R.id.ans_list);
// novo code abaixo
// ListAdapterAns adapterAns = new ListAdapterAns(this,toppings);
// selectListAns.setAdapter(adapterAns);
// selectListAns.setOnItemClickListener(new AnsItemClickListener());
//View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);
//int i = getArguments().getInt(ARG_PLANET_NUMBER);
//String planet = getResources().getStringArray(R.array.planets_array)[i];
//int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
// "drawable", getActivity().getPackageName());
// ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
// getActivity().setTitle(planet);
return rootView;
}
// Async Task to access the web
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) {
// e.printStackTrace();
//Toast.makeText(getApplicationContext(),
// "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
//Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
R.id.content_list_ans,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
//Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
The line is:
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
R.id.content_list_ans,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
The error is :
The constructor SimpleAdapter(SelectAnswerActivity, List<Map<String,String>>, int, String[], int[]) is
undefined.
Is the problem this(context) ?
Try this, using Activity context instead of Fragment
SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), employeeList,
R.id.content_list_ans,
new String[] { "employees" }, new int[] { android.R.id.text1 });
Your reference to the Context is wrong. You cannot have the activity context in the AsynTask class. You should try one of getApplicationContext() or getActivity() instead of this.
Also SelectAnswerActivity is not and Activity, its a Fragment. If it was activity you could have also used SelectAnswerActivity.this
You are referencing the context of the fragment, not the one of your Activity. Try changing that.

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

How do I pass parameter to webservice and get json datas in listview

Hi (fresher to andorid)
I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched datas from DB(sql server 2008) and bind that to android:LISTVIEW.
Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying the result based on the given value instead of that it displays all values.
Here is my webservice code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
Here is my android code(Main.java):
package com.example.cargotracking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView Id;
TextView Status;
TextView DateTime;
Button Btngetdata;
String JobNo;
EditText editText1;
ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
//JSON Node Names
private static final String TAG_CargoTrack = "Cargo";
private static final String TAG_Id = "Id";
private static final String TAG_Status = "Status";
private static final String TAG_DateTime = "DateTime";
JSONArray Cargo = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// List params = new ArrayList();
params.add(new BasicNameValuePair("JobNo","01"));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my json parser code:
package com.example.cargotracking;
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.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.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> 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();
} 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;
}
}
please help me to resolve this.
Thanks in advance

Categories

Resources