How to send Large JSON Data to server using Retrofit? - android

I had created service that retrieves contacts from android device name, mobile number and email and stores in array list with custom object of contacts. I am having 20,000 contacts in my device. I am converting that array list to JSON Array using Gson. And I am sending data to server but request fails. If I am sending small amount of data then API gives successful response. I want to know why I am not able to have success request when there is large data in JSON format.
This is sample format data that i will send to server
[
{
"Name": "FirstName Lastname",
"Phone": "[+123456789012]"
},
{
"Name": "FirstName Lastname",
"Phone": "[+123456789012, +123456789012, +123456789012]",
"Email": "abcd#gmail.com"
},
{
"Name": "FirstName Lastname",
"Phone": "[+123456789012]"
},
{
"Name": "FirstName Lastname",
"Phone": "[]"
}
]
This is print stack trace that I am getting
06-25 17:32:21.816 19421-20008/ D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLException: Write error: ssl=0x40d92618: I/O error during system call, Broken pipe
06-25 17:32:21.826 19421-19421/ W/System.err: javax.net.ssl.SSLException: Write error: ssl=0x40d92618: I/O error during system call, Broken pipe
06-25 17:32:21.856 19421-19421/ W/System.err: at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_write(Native Method)
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLOutputStream.write(OpenSSLSocketImpl.java:719)
at okio.Okio$1.write(Okio.java:79)
at okio.AsyncTimeout$1.write(AsyncTimeout.java:180)
at okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:179)
at okio.RealBufferedSink.writeUtf8(RealBufferedSink.java:54)
at okhttp3.internal.http1.Http1Codec.writeRequest(Http1Codec.java:172)
at okhttp3.internal.http1.Http1Codec.writeRequestHeaders(Http1Codec.java:130)
at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:50)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
Here is my service code that does all stuffs.
public class ContactService extends Service {
String strDate;
#Nullable
CompositeDisposable mDisposable = null;
private UploadContactsUseCase mUploadContactsUseCase;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
//to convert Date to String, use format method of SimpleDateFormat class.
strDate = dateFormat.format(date);
new GetContacts().execute();
stopSelf();
// I don't want this service to stay in memory, so I stop it
// immediately after doing what I wanted it to do.
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
if (mDisposable != null) {
mDisposable.dispose();
mDisposable = null;
}
// I want to restart this service again.
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1),
PendingIntent.getService(this, 0, new Intent(this, ContactService.class), 0));
}
private JSONArray displayContacts() {
int j = 1;
List<ContactUser> contactUserList = new ArrayList<ContactUser>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
Log.i("COUNT: ", String.valueOf(j++));
List<String> listPhones = new ArrayList<String>();
ContactUser contactUser = new ContactUser();
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactUser.setName(name);
if (Integer
.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))
> 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur != null && pCur.moveToNext()) {
String phoneNo = pCur
.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
// Log.i("Contact", name + " " + ":" + " " + phoneNo);
listPhones.add(phoneNo);
// mStoreContacts.add(name + " " + ":" + " " + phoneNo);
}
if (pCur != null) {
pCur.close();
}
}
// get the user's email address
String email = null;
Cursor ce = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
if (ce != null && ce.moveToFirst()) {
email = ce.getString(ce.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// mStoreContacts.add(name + " " + ":" + " " + email);
ce.close();
}
String[] array = listPhones.toArray(new String[0]);
contactUser.setPhone(Arrays.toString(array));
contactUser.setEmail(email);
contactUserList.add(contactUser);
}
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < contactUserList.size(); i++) {
jsonArray.put(contactUserList.get(i).getJSONObject());
}
if (cur != null) {
cur.close();
}
return jsonArray;
}
if (cur != null) {
cur.close();
}
return null;
}
class GetContacts extends AsyncTask<Void, Void, JSONArray> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(ContactService.this, "Starting reading contacts", Toast.LENGTH_SHORT).show();
}
#Override
protected JSONArray doInBackground(Void... voids) {
JSONArray contacts = displayContacts();
return contacts;
}
#Override
protected void onPostExecute(final JSONArray contact) {
super.onPostExecute(contact);
// new JobTask(contact).execute();
try {
Log.i("Contacts:", contact.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
mDisposable = new CompositeDisposable();
mUploadContactsUseCase = new UploadContactsUseCaseImpl();
mDisposable.add(mUploadContactsUseCase
.execute(Preferences.getInstance().getUserEmail(), contact.toString())
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action() {
#Override
public void run() throws Exception {
// handle completion
Toast.makeText(ContactService.this, "Complete", Toast.LENGTH_SHORT).show();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
// handle error
Toast.makeText(ContactService.this, throwable.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}));
}
}
}
This is my network manager class of Retrofit
public class NetworkManager {
/**
* The Constant CONNECTION_TIMEOUT_TIME.
*/
private static final long CONNECTION_TIMEOUT_TIME = 30;
private static final String CURRENT_LANG =
Locale.getDefault().getLanguage().toString() + "-" + Locale.getDefault().getCountry();
private static final String GZIP_DEFLATE = "gzip,deflate";
/**
* The Constant ACCEPT_ENCODING.
*/
private static final String ACCEPT_ENCODING = "Accept-Encoding";
/**
* The Constant CONTENT_TYPE.
*/
private static final String CONTENT_TYPE = "Content-Type";
/**
* The Constant APPLICATION_JSON.
*/
private static final String APPLICATION_JSON = "application/json";
private static final String BASE_URL = "https://mybaseurl.in";
private static SafecodeApiService sInstanceV2 = null;
private static SafecodeApiService sInstanceV2_1 = null;
public static SafecodeApiService getService() {
if (sInstanceV2 == null) {
OkHttpClient client = getHttpClient();
sInstanceV2 = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(GsonFactory.create())).client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build()
.create(SafecodeApiService.class);
}
return sInstanceV2;
}
#NonNull
private static OkHttpClient getHttpClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder().followRedirects(true).followSslRedirects(true)
.retryOnConnectionFailure(true).connectTimeout(CONNECTION_TIMEOUT_TIME, TimeUnit.SECONDS)
.writeTimeout(CONNECTION_TIMEOUT_TIME, TimeUnit.SECONDS)
.readTimeout(CONNECTION_TIMEOUT_TIME, TimeUnit.SECONDS)
.readTimeout(CONNECTION_TIMEOUT_TIME, TimeUnit.SECONDS).cache(null)
.addInterceptor(loggingInterceptor).addInterceptor(new ResponseInterceptor()).build();
}
private static class ResponseInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
try {
Request original = chain.request();
Request request = original.newBuilder().addHeader(CONTENT_TYPE, APPLICATION_JSON)
.addHeader("Connection", "Keep-Alive").addHeader(ACCEPT_ENCODING, GZIP_DEFLATE)
.method(original.method(), original.body()).build();
Response response = chain.proceed(request);
String rawJson = response.body().string();
Log.i("RESPONSE: ", String.format("raw JSON response is: %s", rawJson));
switch (response.code()) {
case HttpURLConnection.HTTP_OK:
// Re-create the response before returning it because body can be read only once
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), rawJson)).build();
case HttpURLConnection.HTTP_UNAVAILABLE:
throw new MaintenanceException("Service Unavailable.");
default:
break;
}
return response;
} catch (SocketTimeoutException exception) {
throw new SocketTimeoutException("timeout");
}
}
}
private static class MaintenanceException extends RuntimeException {
public MaintenanceException(String message) {
super(message);
}
}
}

I am able to send max 50 contacts to server at a time. I had checked this practically on device. I am not able to send all 20000 contacts at same time. I changed my logic I will send one by one contact to server as and when retrieved from ContentResolver. I think this could be the only way and I think problem is with server that is not able to handle max character in post method of API. Thanks to all members who really helped me to resolve this issue.

Related

Why jdbc return null in first time when execute the query?

The below code is working with sql-server db & ZXingScannerView.ResultHandler barcode scanner.
When I scan the barcode for the first time I get null from executed db query and I have to scan the barcode twice to get the result. I checked the barcode scanner lib and everything is working fine and the same to jdbc.
Code for SqlServerConnection.java:
public class SqlServerConnection {
#SuppressLint("NewApi")
public Connection SqlConnection(String server, String database, String user, String password)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + ":1433/" + database + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se){Log.e("error here 1 : ", se.getMessage());}
catch (ClassNotFoundException e){Log.e("error here 2 : ", e.getMessage());}
catch (Exception e){Log.e("error here 3 : ", e.getMessage());}
return connection;
}
}
Code for Search.java:
public class Search extends AsyncTask<String, String, String> {
// Declaring connection variables
Connection con;
public static String ScannerResult;
public static String z = "";
public static Boolean isSuccess = false;
SqlServerConnection sqlsrverconnection = new SqlServerConnection ();
#Override
protected String doInBackground(String... params) {
if (ScannerResult.trim().equals(""))
z = "Please enter User Id and Password";
else {
con = sqlsrverconnection.SqlConnection("mySqlServer", "mydb", "myUser", "Password");
try {
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "SELECT * FROM [EmpDevicesList] WHERE Record='" + ScannerResult + "';";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
Device.setDeviceTag(rs.getString("Record"));
Device.setDeviceType(rs.getString("Type"));
Device.setDeviceBrand(rs.getString("Brand"));
Device.setDeviceModel(rs.getString("Model"));
isSuccess = true;
} else {
z = "Your search - " + ScannerResult + " - did not match any record.\n"
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
Code for ScannActivity.java:
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
MediaTools mediaTools = new MediaTools();
private ZXingScannerView scannerView;
Search search = new Search();
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
#Override
public void onResume() {
super.onResume();
scannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
scannerView.startCamera(); // Start camera on resume
scannerView.setAutoFocus(true);
}
#Override
public void onPause() {
super.onPause();
scannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
Search.ScannerResult = rawResult.getText();
search.execute("");
mediaTools.Beep();
String s1 = Device.getDeviceTag();
String s2 = Device.getDeviceType();
String s3 = Device.getDeviceBrand();
String s4 = Device.getDeviceModel();
Toast.makeText(getBaseContext(),
"Tag : " + s1
+ "\nType : " + s2
+ "\nBrand : " + s3
+ "\nModel : " + s4,
Toast.LENGTH_LONG).show();
finish();
}
}
Table Schema
Record | Type | Brand | Modle
--------------------------------
1002 | PC | HP | X-1
1003 | PC | Dell | 788

Thread Executor not running properly inside loop

I am trying to implement multiple concurrent file uploads using IntentService for which I am using ThreadExecutor. I am iterating through a map and one-by-one and I am fetching the information and instantiating a workerthread. Inside the loop I have executor which is executing those threads. Below is my code.
#Override
protected void onHandleIntent(Intent intent) {
Debug.print("Called handleIntent");
mFileMap = (HashMap<String, Integer>) intent.getSerializableExtra("pdf_info");
mMapSize = mFileMap.size();
Log.e("pdf", mFileMap.toString());
mExecutor = Executors.newFixedThreadPool(2);
mTotalFileSize = getTotalFileSize();
Log.e("total_file_size", mTotalFileSize + "");
ArrayList<UploadWorker> uploadWorkerArrayList = new ArrayList<>();
Iterator it = mFileMap.entrySet().iterator();
for(Map.Entry<String, Integer> entry : mFileMap.entrySet())
{
String filePath = (String) entry.getKey();
Log.e("map_path: ", filePath);
int categoryId = (int) entry.getValue();
Log.e("map_no: ", categoryId + "");
// uploadWorkerArrayList.add(new UploadWorker(filePath, categoryId));
UploadWorker worker = new UploadWorker(filePath, categoryId);
mExecutor.submit(worker);
}
mExecutor.shutdown();
Log.e("workerlist: ", uploadWorkerArrayList.toString());
}
Below is my UploadWorker code.
class UploadWorker implements Runnable {
String filePath;
int categoryId;
public UploadWorker(String filePath, int categoryId) {
this.filePath = filePath;
this.categoryId = categoryId;
}
#Override
public synchronized void run() {
mFile = new File(filePath);
Log.e("uploadworker", filePath);
mParams = new LinkedHashMap<>();
mParams.put("file_type", 2 + "");
mParams.put("file_name", mFile.getName());
mParams.put("category_id", categoryId + "");
notificationId++;
mNotificationMap.put(filePath, notificationId);
createNotification(notificationId, mFile.getName());
int response = uploadPDF(filePath);
if (response == 1) {
JSONObject jObject = null;
String status = null;
try {
jObject = new JSONObject(mServerResponse);
status = jObject.getString("status");
int id = mNotificationMap.get(filePath);
updateNotification(100, id);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("<><>", status);
} else {
Log.e("<><>", "Upload fail");
}
}
}
However it happens that if say my maplist has 2 entries, then the iterator is first fetching both the entries and the executor is uploading only the final entry, that too twice. Please help.

Call an AsyncTask subclass of activity from another class?

I know this kind of questions are maybe too old, but I got stock with this silly thing.
I have an AsyncTask class which is a subclass of an activity class, and right now I want to call it from another class: following codes shows what I mean:
public class STA extends Activity {
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
private static final String TAG = "ListSpdFiles: ";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private String initiator;
private String path;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(String initiator, String path) {
this.initiator = initiator;
this.path = path;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(getApplicationContext(), pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
// tv.setText("task concluded with a null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
//tv.setText("List of files received is:\n" + Arrays.toString(listOfFiles));
}
term();
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
final Global globalVariable = (Global) getApplicationContext();
if (globalVariable.getPasswordButt() == false) {
// Calling Application class (see application tag in AndroidManifest.xml)
// Get name and email from global/application context
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
String username = "/" + getLastAccessedBrowserPage() + ".username" + ".txt";
//String password = "/" + CurrentURL + "password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, username, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setUsername(name);
// getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsUsername(false);
} else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
// globalVariable.setUsernameButt(false);
} else if (globalVariable.getPasswordButt() == true) {
// Calling Application class (see application tag in AndroidManifest.xml)
// final Global globalVariable = (Global) getApplicationContext();
// Get name and email from global/application context
final boolean ispassword = globalVariable.getIsPassword();
if (ispassword == true) {
// String username = "/" + CurrentURL + "username" + ".txt";
String password = "/" + getLastAccessedBrowserPage() + ".password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, password, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setPassword(name);
//getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsPassword(false);
} else if (ispassword == false)
Log.i(TAG, "Wrong Input Type For Password.");
globalVariable.setPasswordButt(false);
// boolpassword=false;
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
Would you please tell me what should I do to fix this code?
Looking over the code I did not see anywhere you referenced anything from the Activity itself besides the application context so you can move the ListSpdFiles class to its own java file and pass it a context into the constructor when you make a new instance of it.
Put this class in a ListSpdFiles.java file so it is no longer an inner class.
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
Context applicationContext;
public ListSpdFiles(Context context, String initiator, String path) {
this.initiator = initiator;
this.path = path;
applicationContext = context.getApplicationContext();
}
// The rest of your code still goes here. Replace other calls to
// getApplicationContext() with the new applicationContext field
}
You can now use this class anywhere a Context is available. You create a new instance by doing:
ListSpdFiles listSpdFilesTask = new ListSpdFiles(context, "someInitiator", "somePath");
listSpdFilesTask.execute();

How to return Object which is inside anonymous inner class?

I've created this code to access user from my database for Login purpose. I can access the object 'st' when I'm inside OnResponse method but when I try to return return the object, it gives me null. Also when I try to access this st object before returning, it gives NullPointerException. What is the exact problem?
public class ServerRequests {
ProgressDialog progressDialog;
public static user_Student st;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://prem-pc:8989/";
Context ct;
public ServerRequests(Context context) {
ct = context;
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait....");
}
public ServerRequests() {
}
public user_Student fetchUserDataInBackground(user_Student user) {
progressDialog.show();
Toast.makeText(ct, "Data in background: ", Toast.LENGTH_SHORT).show();
user_Student ust = doInBackground(user);
progressDialog.dismiss();
return ust;
}
public user_Student doInBackground(user_Student user) {
String URL = SERVER_ADDRESS + "connect.php?prn=" + user.prn + "&password=" + user.password;
RequestQueue req = Volley.newRequestQueue(ct);
Toast.makeText(ct, "Do in Background", Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jObject) {
try {
// Parsing json object response
// response will be a json object
if (jObject.length() == 0) {
st = null;
Toast.makeText(ct, "Null JSON Object", Toast.LENGTH_SHORT).show();
} else {
String prn = jObject.getString("prn");
String fname = jObject.getString("fname");
String mname = jObject.getString("mname");
String lname = jObject.getString("lname");
String clas = jObject.getString("clas");
String dept = jObject.getString("dept");
String batch = jObject.getString("batch");
String scontact = jObject.getString("scontact");
String pcontact = jObject.getString("pcontact");
String email = jObject.getString("email");
String password = jObject.getString("password");
String dob = jObject.getString("dob");
st = new user_Student(prn, fname, mname, lname, clas, dept, batch, scontact, pcontact, email, password, dob);
Toast.makeText(ct, "JSON Object:" + st.fname, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ct, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ct, error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog
}
});
req.add(jsonObjReq);
//Toast.makeText(ct,"DO in back End"+st.fname,Toast.LENGTH_SHORT).show();
return st;
}
}
You can't return from anonymous inner classes, but you could create a method inside ServerRequests that takes a user_Student as a parameter and call that method from within onResponse. This method could then do whatever you need.
You must use AsyncTask to do funtion doInBackground(user_Student user)
You can view this post to understand AsyncTask:
How to use AsyncTask correctly in Android

login issue using twitter api in android

what is the procedure to login throw twitter api1.1.
i have used old api that will show me twitter connection failed because of api 1 is deprecated.
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener()
{
public void onComplete(String value)
{
getTwitterDetail();
}
public void onError(String value) {
Toast.makeText(LoginActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
LOG
{"errors": [{"message": "The Twitter REST API v1 is no longer active.
Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}
As you see from error log API v.1 is no longer active and everybody must migrate to v1.1. In API v1.1. you must log in via OAUTH to get connected. So you also have to register your app on dev.twitter.com.
You can find below example here
public class Main extends Activity{
public static final String TAG = Main.class.getSimpleName();
public static final String TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT = "..."; //cannot share more then 2 lins, sorry
public static final String TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT = "...";
public static final String TWITTER_OAUTH_AUTHORIZE_ENDPOINT = "...";
private CommonsHttpOAuthProvider commonsHttpOAuthProvider;
private CommonsHttpOAuthConsumer commonsHttpOAuthConsumer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonsHttpOAuthProvider = new CommonsHttpOAuthProvider(TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT,
TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT, TWITTER_OAUTH_AUTHORIZE_ENDPOINT);
commonsHttpOAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
commonsHttpOAuthProvider.setOAuth10a(true);
TwDialog dialog = new TwDialog(this, commonsHttpOAuthProvider, commonsHttpOAuthConsumer,
dialogListener, R.drawable.android);
dialog.show();
}
private Twitter.DialogListener dialogListener = new Twitter.DialogListener() {
public void onComplete(Bundle values) {
String secretToken = values.getString("secret_token");
Log.i(TAG,"secret_token=" + secretToken);
String accessToken = values.getString("access_token");
Log.i(TAG,"access_token=" + accessToken);
new Tweeter(accessToken,secretToken).tweet(
"Tweet from sample Android OAuth app. unique code: " + System.currentTimeMillis());
}
public void onTwitterError(TwitterError e) { Log.e(TAG,"onTwitterError called for TwitterDialog",
new Exception(e)); }
public void onError(DialogError e) { Log.e(TAG,"onError called for TwitterDialog", new Exception(e)); }
public void onCancel() { Log.e(TAG,"onCancel"); }
};
public static final Pattern ID_PATTERN = Pattern.compile(".*?\"id_str\":\"(\\d*)\".*");
public static final Pattern SCREEN_NAME_PATTERN = Pattern.compile(".*?\"screen_name\":\"([^\"]*).*");
public class Tweeter {
protected CommonsHttpOAuthConsumer oAuthConsumer;
public Tweeter(String accessToken, String secretToken) {
oAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
oAuthConsumer.setTokenWithSecret(accessToken, secretToken);
}
public boolean tweet(String message) {
if (message == null && message.length() > 140) {
throw new IllegalArgumentException("message cannot be null and must be less than 140 chars");
}
// create a request that requires authentication
try {
HttpClient httpClient = new DefaultHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.appendPath("statuses").appendPath("update.json")
.appendQueryParameter("status", message);
Uri man = builder.build();
HttpPost post = new HttpPost("http://twitter.com" + man.toString());
oAuthConsumer.sign(post);
HttpResponse resp = httpClient.execute(post);
String jsonResponseStr = convertStreamToString(resp.getEntity().getContent());
Log.i(TAG,"response: " + jsonResponseStr);
String id = getFirstMatch(ID_PATTERN,jsonResponseStr);
Log.i(TAG,"id: " + id);
String screenName = getFirstMatch(SCREEN_NAME_PATTERN,jsonResponseStr);
Log.i(TAG,"screen name: " + screenName);
final String url = MessageFormat.format("https://twitter.com/#!/{0}/status/{1}",screenName,id);
Log.i(TAG,"url: " + url);
Runnable runnable = new Runnable() {
public void run() {
((TextView)Main.this.findViewById(R.id.textView)).setText("Tweeted: " + url);
}
};
Main.this.runOnUiThread(runnable);
return resp.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG,"trying to tweet: " + message, e);
return false;
}
}
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
public static String getFirstMatch(Pattern pattern, String str){
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return matcher.group(1);
}
return null;
}

Categories

Resources