I've made working source codes on synchronizing database before but suddenly it's not working now. Here, I'm trying to read my records in local database in the DB_User class. But it returned java.lang.NullPointerException. So this is what I made.
This is the stacktrace of my error
01-15 06:42:20.080: I/ActivityManager(60): Displayed activity com.yolanda.ta/.DBSynchronizer: 387 ms (total 387 ms)
01-15 06:42:40.639: D/dalvikvm(1147): GC_FOR_MALLOC freed 2008 objects / 125592 bytes in 74ms
01-15 06:43:21.149: D/dalvikvm(1147): GC_FOR_MALLOC freed 777 objects / 219464 bytes in 79ms
01-15 06:44:02.018: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404856 bytes in 67ms
01-15 06:44:35.578: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404976 bytes in 78ms
01-15 06:44:58.399: W/dalvikvm(1147): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-15 06:44:58.411: E/AndroidRuntime(1147): FATAL EXCEPTION: Thread-8
01-15 06:44:58.411: E/AndroidRuntime(1147): java.lang.NullPointerException
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.fetchLocal(ThreadUser.java:192)
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.run(ThreadUser.java:59)
01-15 06:44:58.492: W/ActivityManager(60): Force finishing activity com.yolanda.ta/.DBSynchronizer
and this is fetchLocal() to get data from database which I call it to get data from the local database
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
and this is the method of getAllRow3()
public Cursor getAllRow3()
{
Cursor c = db.query(NAMA_TABEL, new String[]{ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME}, null, null, null, null, null, null);
return c;
}
and this is my table structure
public class DB_User {
private static final String ROW_ID = "IDUser";
private static final String ROW_NAMAL = "NamaLogin";
private static final String ROW_NAMA ="NamaUser";
private static final String ROW_PW ="PasswordUser";
private static final String ROW_ALAMAT ="AlamatUser";
private static final String ROW_TELEPON ="TeleponUser";
private static final String ROW_LEVEL ="LevelUser";
private static final String ROW_STATUS ="StatusUser";
private static final String ROW_TIME ="Waktu";
private static final String NAMA_DB = "TA";
private static final String NAMA_TABEL = "User";
private static final int DB_VERSION = 1;
private static int batas = 5;
private static final String CREATE_TABLE = "create table if not exists "+ NAMA_TABEL +" ("+ ROW_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
ROW_NAMAL +" VARCHAR not null, "+ ROW_NAMA +" VARCHAR not null, " + ROW_PW + " VARCHAR not null, " + ROW_ALAMAT + " VARCHAR not null, "
+ ROW_TELEPON + " VARCHAR, "+ ROW_LEVEL+ " VARCHAR not null, " + ROW_STATUS + " INTEGER not null, "+ROW_TIME+" LONG not null)";
I don't have any idea since the other activity can get exactly the same data using the same query while my thread can't. Any suggestion is welcome.
EDIT:
line 192: Cursor user = mDbHelper.getAllRow3();
line 59: String[] LocalRowID = fetchLocal(0);
Here is my ThreadUser codes:
public class ThreadUser extends Thread implements Runnable {
private boolean RunSync = false;
private DB_User mDbHelper;
private long sleeptime;
public void setDatabase(DB_User mDbHelper)
{
this.mDbHelper = mDbHelper;
}
public void setRun(boolean set)
{
RunSync = set;
}
public void setDelay(long delay)
{
sleeptime = delay;
}
#Override
public void run()
{
while(RunSync)
{
String[] RemoteID = fetch("http://10.0.2.2/project/User.php?ct=Sel_IDUser");
String[] RemoteNamaL = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaLogin");
String[] RemoteNama = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaUser");
String[] RemotePassword = fetch("http://10.0.2.2/project/User.php?ct=Sel_PasswordUser");
String[] RemoteAlamat = fetch("http://10.0.2.2/project/User.php?ct=Sel_AlamatUser");
String[] RemoteTelepon = fetch("http://10.0.2.2/project/User.php?ct=Sel_TeleponUser");
String[] RemoteLevel = fetch("http://10.0.2.2/project/User.php?ct=Sel_LevelUser");
String[] RemoteStatus = fetch("http://10.0.2.2/project/User.php?ct=Sel_StatusUser");
String[] RemoteTime = fetch("http://10.0.2.2/project/User.php?ct=Sel_Waktu");
//ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME
String[] LocalRowID = fetchLocal(0);
String[] LocalNamaL = fetchLocal(1);
String[] LocalNama = fetchLocal(2);
String[] LocalPassword = fetchLocal(3);
String[] LocalAlamat = fetchLocal(4);
String[] LocalTelepon = fetchLocal(5);
String[] LocalLevel = fetchLocal(6);
String[] LocalStatus = fetchLocal(7);
String[] LocalTime = fetchLocal(8);
Calendar cal = Calendar.getInstance();;
for(int i = 1; i < RemoteID.length; i++)
{ Log.e("index remote1", Integer.toString(i));
for(int j = 0; j < LocalRowID.length; j++)
{
Log.e("indexlocal1", Integer.toString(j));
if(RemoteID[i].equalsIgnoreCase(LocalRowID[j]))
{
if(Long.parseLong(RemoteTime[i]) > Long.parseLong(LocalTime[j]))
{
// //id, namal, nama, alamat, password, telepon, level, status, time
mDbHelper.updateBaris2(Integer.parseInt(LocalRowID[j]), RemoteNamaL[i],
RemoteNama[i], RemoteAlamat[i],RemotePassword[i],
RemoteTelepon[i], RemoteLevel[i], Integer.parseInt(RemoteStatus[i]), cal.getTimeInMillis());
break;
}
else if (Long.parseLong(RemoteTime[i]) < Long.parseLong(LocalTime[j]))
{
call("http://10.0.2.2/project/User.php?ct=EDT&namal="+LongData(LocalNamaL[j].toString())+
"&nama="+LongData(LocalNama[j].toString())+"&pw="+LongData(LocalPassword[j].toString())+"&alamat="+LongData(LocalAlamat[j].toString())+
"&telepon="+LongData(LocalTelepon[j].toString())+"&level="+LongData(LocalLevel[j].toString())+"&status="+LocalStatus[j]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[j].toString());
break;
}
}
}
if (LocalRowID.length + 1 > RemoteID.length)
{//namal, nama, alamat, password, telepon, level, status, time
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[LocalRowID.length-1].toString())+
"&nama="+LongData(LocalNama[LocalRowID.length-1].toString())+"&pw="+LongData(LocalPassword[LocalRowID.length-1].toString())+"&alamat="+LongData(LocalAlamat[LocalRowID.length-1].toString())+
"&telepon="+LongData(LocalTelepon[LocalRowID.length-1].toString())+"&level="+LongData(LocalLevel[LocalRowID.length-1].toString())+"&status="+LocalStatus[LocalRowID.length-1]+"&time="
+cal.getTimeInMillis());
Log.e("nambah server","voila");
break;
}
catch (Exception e){Log.e("walah",e.toString());}
}
else
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
for(int i = 0; i < LocalRowID.length-1; i++)
{ Log.e("index local2", Integer.toString(i));
if(RemoteID.length <= 1)
{
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[i].toString())+
"&nama="+LongData(LocalNama[i].toString())+"&pw="+LongData(LocalPassword[i].toString())+"&alamat="+LongData(LocalAlamat[i].toString())+
"&telepon="+LongData(LocalTelepon[i].toString())+"&level="+LongData(LocalLevel[i].toString())+"&status="+LocalStatus[i]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[i].toString());
}
catch(Exception e){
Log.e("wooooy", e.toString());
}
}
for(int j = 1; j < RemoteID.length; j++)
{
Log.e("indexremote2", Integer.toString(j));
if(LocalRowID[i].equalsIgnoreCase(RemoteID[j]))
{
break;
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
if (RemoteID.length-1 > LocalRowID.length)
{
i-=1;
try{
mDbHelper.addRow2(RemoteNamaL[RemoteID.length-1], RemoteNama[RemoteID.length-1], RemoteAlamat[RemoteID.length-1], RemotePassword[RemoteID.length-1],
RemoteTelepon[RemoteID.length-1], RemoteLevel[RemoteID.length-1], Integer.parseInt(RemoteStatus[RemoteID.length-1]), cal.getTimeInMillis());
break;
}
catch(Exception e){
Log.e("wuuuy", e.toString());
}
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
try {
sleep(sleeptime);
} catch (InterruptedException e) {
break;
}
}
}
public String LongData (String Data)
{
String LongData ="";
for (int i = 0; i < Data.length(); i++)
{
if (Data.charAt(i)==' ')
{
LongData += '~';
}
else
LongData += Data.charAt(i);
}
return LongData;
}
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
public String[] fetch(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpRequestBase httpRequest = null;
HttpResponse httpResponse = null;
InputStream inputStream = null;
String response = "";
StringBuffer buffer = new StringBuffer();
httpRequest = new HttpGet(url);
try
{
httpResponse = httpclient.execute(httpRequest);
}
catch (ClientProtocolException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream = httpResponse.getEntity().getContent();
}
catch (IllegalStateException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
byte[] data = new byte[512];
int len = 0;
try
{
while(-1 != (len = inputStream.read(data)))
{
buffer.append(new String(data,0,len));
}
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream.close();
}
catch (IOException el)
{
el.printStackTrace();
}
response = buffer.toString();
StringParser parser = new StringParser();
ArrayList<Object> output = parser.Parse(response);
Object[] Output = output.toArray();
String[] content = new String[Output.length];
for (int i = 0; i < content.length; i++)
{
content[i] = Output[i].toString();
}
return content;
}
public String call(String url)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try
{
in = OpenHttpConnection(url);
}
catch (IOException el) {
el.printStackTrace();
return "Error: " + el.getMessage();
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try
{
while((charRead = isr.read(inputBuffer)) > 0)
{
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
return "Error 02";
}
return str;
}
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http Connection");
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error Connecting");
}
return in;
}
}`
First of all, your code don't have code line number, so we don't know which line is "ThreadUser.java:192" and "ThreadUser.java:59".
Actually this problem may be a synchronized problem, please provide more code detail about TheadUser.java code. If so please add synchronized to method or synchronized block to solve this issue.
Related
I am developing an android application in which I want to retrieve the image stored in SQL server database as shown in screenshot:
I have written a code for that but application will only retrieve the title column value and successfully shows in textview but in imageview nothing displays.Every kind of help is appreciated. Below is my code for that:
public class Menu_listen extends Fragment implements View.OnClickListener {
Connection con;
TextView t;
ImageView img;
String un,pass,db,ip,in;
private String abc;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("abc");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View InputFragmentView = inflater.inflate(R.layout.menu_1, container, false);
t = (TextView) InputFragmentView.findViewById(R.id.track_title);
img=(ImageView) InputFragmentView.findViewById(R.id.track_image);
ip = "192.168.***.**";
in="SQLEXPRESS";
db = "Testaudio";
un = "**";
pass = "****";
Check check1 = new Check();// this is the Asynctask, which is used to process in background to reduce load on app process
check1.execute("");
return InputFragmentView;
}
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public class Check extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
}
#Override
protected void onPostExecute(String r)
{
if(isSuccess)
{
Toast.makeText(getActivity() , "Successfull" , Toast.LENGTH_SHORT).show();
t.setText(getAbc());
byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length);
img.setImageBitmap(decodebitmap);
}
}
#Override
protected String doInBackground(String... params)
{
try
{
con = connectionclass(un, pass, db, ip,in);
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
String query = "select * from getImg";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs != null && rs.next())
{
z = "successful";
isSuccess=true;
setAbc(rs.getString(3));
z=rs.getString(2);
}
con.close();
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server,String instance) {
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 + "/" + database + ";instance=" + instance + ";user=" + user + ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("error here 1 : ", se.getMessage());
t.setText(se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("error here 2 : ", e.getMessage());
t.setText(e.getMessage());
} catch (Exception e) {
Log.e("error here 3 : ", e.getMessage());
t.setText(e.getMessage());
}
return connection;
}
}
Here the code i used for my app
This code will take a image from url and convert is to a byte array
byte[] logoImage = getLogoImage(IMAGEURL);
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
To save the image to db i used this code.
public void insertUser(){
SQLiteDatabase db = dbHelper.getWritableDatabase();
String delSql = "DELETE FROM ACCOUNTS";
SQLiteStatement delStmt = db.compileStatement(delSql);
delStmt.execute();
String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
SQLiteStatement insertStmt = db.compileStatement(sql);
insertStmt.clearBindings();
insertStmt.bindString(1, Integer.toString(this.accId));
insertStmt.bindString(2,this.accName);
insertStmt.bindBlob(3, this.accImage);
insertStmt.executeInsert();
db.close();
}
To retrieve the image back this is code i used.
public Account getCurrentAccount() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String sql = "SELECT * FROM ACCOUNTS";
Cursor cursor = db.rawQuery(sql, new String[] {});
if(cursor.moveToFirst()){
this.accId = cursor.getInt(0);
this.accName = cursor.getString(1);
this.accImage = cursor.getBlob(2);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
if(cursor.getCount() == 0){
return null;
} else {
return this;
}
}
Finally to load this image to a imageview
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));
How to upload a video to a particular YouTube account from my android app i have followed https://github.com/youtube/yt-direct-lite-android but its not very documented.
I have tried
public class YoutubeUploader {
private static final String TAG = "YoutubeUploader";
// After creating project at http://www.appspot.com DEFAULT_YTD_DOMAIN == <Developers Console Project ID>.appspot.com [ You can find from Project -> Administration -> Application settings]
//public static final String DEFAULT_YTD_DOMAIN = "developerconsolid.appspot.com";
// I used Google APIs Console Project Title as Domain name:
//public static final String DEFAULT_YTD_DOMAIN_NAME = "Domain Name";
//From Google Developer Console from same project (Created by SHA1; project package)
//Example https://console.developers.google.com/project/apps~gtl-android-youtube-test/apiui/credential
public static final String DEVELOPER_KEY = "<MY_DEVELOPER_KEY>";
// CLIENT_ID == Google APIs Console Project Number:
public static final String CLIENT_ID = "157613";
public static final String YOUTUBE_AUTH_TOKEN_TYPE = "youtube";
private static final String AUTH_URL = "https://www.google.com/accounts/ClientLogin";
// Uploader's user-name and password
private static final String USER_NAME = "my#gmail.com";
private static final String PASSWORD = "mypassword";
private static final String INITIAL_UPLOAD_URL = "https://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads";
private static String getClientAuthToken() {
try {
URL url = new URL(AUTH_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String template = "Email=%s&Passwd=%s&service=%s&source=%s";
String userName = USER_NAME; // TODO
String password = PASSWORD; // TODO
String service = YOUTUBE_AUTH_TOKEN_TYPE;
String source = CLIENT_ID;
userName = URLEncoder.encode(userName, "UTF-8");
password = URLEncoder.encode(password, "UTF-8");
String loginData = String.format(template, userName, password, service, source);
OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outStreamWriter.write(loginData);
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200) {
Log.d(TAG, "Got an error response : " + responseCode + " " + urlConnection.getResponseMessage());
throw new IOException(urlConnection.getResponseMessage());
} else {
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("Auth=")) {
String split[] = line.split("=");
String token = split[1];
Log.d(TAG, "Auth Token : " + token);
return token;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String upload(YoutubeUploadRequest uploadRequest, ProgressListner listner, Activity activity) {
totalBytesUploaded = 0;
String authToken = getClientAuthToken();
if(authToken != null) {
String uploadUrl = uploadMetaData(uploadRequest, authToken, activity, true);
File file = getFileFromUri(uploadRequest.getUri(), activity);
long currentFileSize = file.length();
int uploadChunk = 1024 * 1024 * 3; // 3MB
int start = 0;
int end = -1;
String videoId = null;
double fileSize = currentFileSize;
while (fileSize > 0) {
if (fileSize - uploadChunk > 0) {
end = start + uploadChunk - 1;
} else {
end = start + (int) fileSize - 1;
}
Log.d(TAG, String.format("start=%s end=%s total=%s", start, end, file.length()));
try {
videoId = gdataUpload(file, uploadUrl, start, end, authToken, listner);
fileSize -= uploadChunk;
start = end + 1;
} catch (IOException e) {
Log.d(TAG,"Error during upload : " + e.getMessage());
}
}
if (videoId != null) {
return videoId;
}
}
return null;
}
public static int totalBytesUploaded = 0;
#SuppressLint("DefaultLocale")
#SuppressWarnings("resource")
private static String gdataUpload(File file, String uploadUrl, int start, int end, String clientLoginToken, ProgressListner listner) throws IOException {
int chunk = end - start + 1;
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
FileInputStream fileStream = new FileInputStream(file);
URL url = new URL(uploadUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", String.format("GoogleLogin auth=\"%s\"", clientLoginToken));
urlConnection.setRequestProperty("GData-Version", "2");
urlConnection.setRequestProperty("X-GData-Client", CLIENT_ID);
urlConnection.setRequestProperty("X-GData-Key", String.format("key=%s", DEVELOPER_KEY));
// some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(chunk);
urlConnection.setRequestProperty("Content-Type", "video/3gpp");
urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end,
file.length()));
Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));
OutputStream outStreamWriter = urlConnection.getOutputStream();
fileStream.skip(start);
double currentFileSize = file.length();
int bytesRead;
int totalRead = 0;
while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
outStreamWriter.write(buffer, 0, bytesRead);
totalRead += bytesRead;
totalBytesUploaded += bytesRead;
double percent = (totalBytesUploaded / currentFileSize) * 100;
if(listner != null){
listner.onUploadProgressUpdate((int) percent);
}
System.out.println("GTL You tube upload progress: " + percent + "%");
/*
Log.d(LOG_TAG, String.format(
"fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
totalBytesUploaded, percent));
*/
//dialog.setProgress((int) percent);
// TODO My settings
if (totalRead == (end - start + 1)) {
break;
}
}
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "responseCode=" + responseCode);
Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());
try {
if (responseCode == 201) {
String videoId = parseVideoId(urlConnection.getInputStream());
return videoId;
} else if (responseCode == 200) {
Set<String> keySet = urlConnection.getHeaderFields().keySet();
String keys = urlConnection.getHeaderFields().keySet().toString();
Log.d(TAG, String.format("Headers keys %s.", keys));
for (String key : keySet) {
Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
}
Log.w(TAG, "Received 200 response during resumable uploading");
throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage()));
} else {
if ((responseCode + "").startsWith("5")) {
String error = String.format("responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage());
Log.w(TAG, error);
// TODO - this exception will trigger retry mechanism to kick in
// TODO - even though it should not, consider introducing a new type so
// TODO - resume does not kick in upon 5xx
throw new IOException(error);
} else if (responseCode == 308) {
// OK, the chunk completed succesfully
Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage()));
} else {
// TODO - this case is not handled properly yet
Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
urlConnection.getResponseMessage(), uploadUrl));
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
private static String parseVideoId(InputStream atomDataStream) throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(atomDataStream);
NodeList nodes = doc.getElementsByTagNameNS("*", "*");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String nodeName = node.getNodeName();
if (nodeName != null && nodeName.equals("yt:videoid")) {
return node.getFirstChild().getNodeValue();
}
}
return null;
}
private static File getFileFromUri(Uri uri, Activity activity) {
try {
String filePath = null;
String[] proj = { Video.VideoColumns.DATA };
Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
if(cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(Video.VideoColumns.DATA);
filePath = cursor.getString(column_index);
}
cursor.close();
//String filePath = cursor.getString(cursor.getColumnIndex(Video.VideoColumns.DATA));
File file = new File(filePath);
cursor.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String uploadMetaData(YoutubeUploadRequest uploadRequest, String clientLoginToken, Activity activity, boolean retry) {
try {
File file = getFileFromUri(uploadRequest.getUri(), activity);
if(file != null) {
String uploadUrl = INITIAL_UPLOAD_URL;
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", String.format("GoogleLogin auth=\"%s\"", clientLoginToken));
connection.setRequestProperty("GData-Version", "2");
connection.setRequestProperty("X-GData-Client", CLIENT_ID);
connection.setRequestProperty("X-GData-Key", String.format("key=%s", DEVELOPER_KEY));
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/atom+xml");
connection.setRequestProperty("Slug", file.getAbsolutePath());
String title = uploadRequest.getTitle();
String description = uploadRequest.getDescription();
String category = uploadRequest.getCategory();
String tags = uploadRequest.getTags();
String template = readFile(activity, R.raw.gdata).toString();
String atomData = String.format(template, title, description, category, tags);
/*String template = readFile(activity, R.raw.gdata_geo).toString();
atomData = String.format(template, title, description, category, tags,
videoLocation.getLatitude(), videoLocation.getLongitude());*/
OutputStreamWriter outStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outStreamWriter.write(atomData);
outStreamWriter.close();
int responseCode = connection.getResponseCode();
if (responseCode < 200 || responseCode >= 300) {
// The response code is 40X
if ((responseCode + "").startsWith("4") && retry) {
Log.d(TAG, "retrying to fetch auth token for ");
clientLoginToken = getClientAuthToken();
// Try again with fresh token
return uploadMetaData(uploadRequest, clientLoginToken, activity, false);
} else {
return null;
}
}
return connection.getHeaderField("Location");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static CharSequence readFile(Activity activity, int id) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
}
// Chomp the last newline
buffer.deleteCharAt(buffer.length() - 1);
return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
/**
* Closes the specified stream.
*
* #param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
public static interface ProgressListner {
void onUploadProgressUpdate(int progress);
}
I am getting 404 error in getClientAuthToken() method.I think "https://www.google.com/accounts/ClientLogin";deprecated by google any alternative to this
plz help me
I did added async library at my project and checked already, I don't know why code flow doesn't go in to asynctask
my Update code doesn't execute.
in this line my update calss doesnt run
dataupdate.execute();
CODE:
public class Update extends AsyncTask<Void, Void, Integer> {
private String User;
private final String mLink;
public Update(String user) {
User = user;
mLink = "http://www./Update.php";
}
#Override
protected Integer doInBackground(Void... params) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
}
return null;
}
}
Main:
showProgress(true);
dataupdate = new Update(username);
dataupdate.execute();
// dataupdate.execute((Void) null);
showProgress(false);
do it like this
public class Update extends AsyncTask<String, String, Integer> {
#Override
protected Integer doInBackground(String... params) {
User user=params[0]; //get string user value here
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(user, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
e.printstacktrace();
}
return null;
}
}
to run
//put username value in execute
new Update()execute(username);
I receive data in webservice and insert in sqlite database Android but if filed is empty repeat before filed As far as new filed no empty and repeat ...
please help me:
public class gfc extends AsyncTask {
private String Link = "";
private String Count = "";
private String tid = "";
private String tim = "";
private String tuser = "";
private String tusername = "";
private String tmatn = "";
private String tcomments = "";
private String tlikes = "";
private String tdate = "";
private String tip_addr = "";
private database db;
public gfc(String link, String count, Context c) {
Link = link;
Count = count;
db = new database(c);
}
#Override
protected String doInBackground(Object... arg0) {
try {
String data = URLEncoder.encode("count", "UTF8") + "=" + URLEncoder.encode(Count, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
db.open();
while ((line = reader.readLine()) != null) {
int f = 0;
int c = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
String temp = line.substring(f, i);
if (c == 0) {
tid = temp;
}
if (c == 1) {
tdate = temp;
}
if (c == 2) {
tuser = temp;
}
if (c == 3) {
tusername = temp;
}
if (c == 4) {
tip_addr = temp;
}
if (c == 5) {
tcomments = temp;
}
if (c == 6) {
tlikes = temp;
}
if (c == 7) {
tim = temp;
}
if (c == 8) {
tmatn = temp.replace("^", "\n");
}
c += 1;
f = i + 1;
}
}
db.insert(tid, tuser, tusername, tmatn, tcomments, tlikes, tdate, tip_addr, tim);
sb.append("t");
}
db.close();
index.res = sb.toString();
} catch (Exception e) {}
return "";
}
}
My webservice;
[WebMethod]
public int insertNhanVien(string[] arr)
{
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Bai1;Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
And code in android:
private boolean insertNhanVient() {
boolean result = false;
try {
String NAMESPACE ="http://tempuri.org/";
String METHOD_NAME ="insertNhanVien";
String URL ="http://localhost:10829/WebSite/Service.asmx";
String SOAP_ACTIONS = NAMESPACE + "/" + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String [] arr =new String[3];
arr[0]="le,12";
arr[1]="hoang,33";
arr[2]="nhung,23";
request.addProperty("arr", arr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidhttpTranport = new HttpTransportSE(URL);
try {
androidhttpTranport.call(SOAP_ACTIONS, envelope);
} catch (IOException e3) {
result = false;
} catch (XmlPullParserException e3) {
result = false;
}
Object responseBody = null;
try {
responseBody = envelope.getResponse();
String t = responseBody.toString();
if (t.equals("1")) {
result = true;
}
} catch (SoapFault e2) {
result = false;
}
} catch (Exception e) {
result = false;
} finally {
}
return result;
}
Why show exception: java.lang.RuntimeException: Cannot serialize: [Ljava.lang.String;#4051d0a0 ?
you can't pass whole array.. so you have to use seprator ## in String ..and pass it service... and change on service respectivley.
String commasepratedString="";
for(int i=0;i<arr.length();i++)
{
if(i!=(arr.length-1))
{
commasepratedString=commasepratedString+arr[i]+"##";
}
else
{
commasepratedString=commasepratedString+arr[i];
}
}
request.addProperty("arr", commasepratedString);
and change service code like this way
[WebMethod]
public int insertNhanVien(string commasepratedString)
{
String arr[] = commasepratedString.Split('##');
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;InitialCatalog=Bai1; Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
replace this line
request.addProperty("arr", arr);
with this
request.addProperty("arr", arr[0]);
you cannot pass whole array.you should pass one element of it.
Update
You can add multiple properties like
request.addProperty("prop1", arr[0]);
request.addProperty("prop2", arr[1]);
request.addProperty("prop3", arr[2]);