how to upload a video to YouTube using my android app - android

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

Related

Android SDK AsyncTask doInBackground not running

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);

Best method to send image and a text from android to wcf service

I need to send an image and text from android to wcf service, tried with http client with multipart but no luck, kindly suggest.
send image using multipartBuilder and send text separately as json via http url connection, the below code for sending image to wcf service is this
Android code
public String postFiless( byte[] imgbyt, String urlString) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
byte[] data = imgbyt;
String fileName = String.format("File_%d.jpg",new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
builder.addPart("image", bab);
final HttpEntity entity = builder.build();
post.setEntity(entity );
HttpResponse response = client.execute(post);
Log.e("result code", ""+response.getStatusLine().getStatusCode());
return getContent(response);
}
public static String getContent(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null)
{
content += body + "\n";
}
return content.trim();
}
WCF CODE TO GET THE IMAGE STREAM SENT FROM ANDROID
Three steps to upload image using Multipart Parser from android to WCF Rest Service
//Step 1
//WCF Rest Interface
// Namespace
using System.IO;
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/UploadImg")]
string UploadImg(Stream fileStream);
Step 2
// WCF Implementation class
// Name spaces
using System.IO;
public string UploadImg(Stream fileStream) {
string strRet = string.Empty;
string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; // System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
string Path = HttpContext.Current.Server.MapPath("~/Photos");// System.Web.Hosting.HostingEnvironment.MapPath("~/Photos/");// HttpContext.Current.Server.MapPath("~/Photos/")
try {
MultipartParser parser = new MultipartParser(fileStream);
if (parser.Success) {
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
Encoding encoding = Encoding.UTF8;
FileStream fileToupload = new FileStream(Path + "/" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
fileStream.Close();
strRet= fileName;
} else {
return "Image Not Uploaded";
} }
catch (Exception ex) {
// handle the error
}
return strRet;
}
Step 3
// MultipartParser class
//Namespace
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class MultipartParser {
public IDictionary<string, string> Parameters = new Dictionary<string, string>();
public MultipartParser(Stream stream) {
this.Parse(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding) {
this.Parse(stream, encoding);
}
public string getcontent(Stream stream, Encoding encoding) {
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in sections) {
Match nameMatch = new Regex(#"(?<=name\=\"")(.*?)(?=\"")").Match(s);
string name = nameMatch.Value.Trim().ToLower();
if (!string.IsNullOrWhiteSpace(name)) {
int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;
}
}
string strRet = ""; //Parameters["name"];
return strRet;
}
private void Parse(Stream stream, Encoding encoding) {
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1) {
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
//re = new Regex(#"(?<=name\=\"")(.*?)(?=\"")");
//Match nameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success) {
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true; }
} }
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex) {
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1) {
while ((startPos + index) < searchWithin.Length) {
if (searchWithin[startPos + index] == serachFor[index]) {
index++;
if (index == serachFor.Length) {
return startPos;
}
} else {
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1) {
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream) {
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream()) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success {
get;
private set;
}
public string ContentType {
get;
private set;
}
public string Filename {
get;
private set;
}
public byte[] FileContents {
get;
private set;
}
public string Imgname {
get;
private set;
} }
// End of Wcf rest Service Code

NanoHTTPD How to save uploaded file to sdcard folder

How to save uploaded file to sdcard folder , currently it stores to /data/data/cache folder with filename like "NanoHTTPD-some random number".
I am not able to copy it to any folder location in sdcard.
I would like to save the file to a pre-mentioned folder location in sdcard with the same name as the original file name was uploaded from my html page.
I have tried all sort of codes .But file copy fails all the time.
1)Not able to get correct location of temp file.
2)Not getting original filename that the form was posted with
Here is my implementation .
Please help i am stuck.
public class HttpMultimediaServer extends NanoHTTPD {
private static final String TAG = "HttpMultimediaServer";
private FileInputStream fileInputStream;
public HttpMultimediaServer() {
super(12345);
this.setTempFileManagerFactory(new ExampleManagerFactory());
}
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
Log.e("handle", "url>>" + uri);
if (uri.contains(filesOnly)) {
isfilesOnly = true;
uri = "/";
} else
isfilesOnly = false;
uri = uri.replace("%20", " ");
try {
uri=new String (uri.getBytes ("iso-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
File filePathServer = new File(uri);
if (method==Method.POST) {
try {
Map<String, String> hdrs=session.getHeaders();
Map<String, String> params=session.getParms();
Map<String, String> files = new HashMap<String, String>();
session.parseBody(files);
Set<String> keys = files.keySet();
for(String key: keys){
String name = key;
String loaction = files.get(key);
File tempfile = new File(loaction);
String tempFileName = files.get(loaction).toString();
File fileToMove = new File(tempFileName);
// temp file path returned by NanoHTTPD
String p =Environment.getExternalStorageDirectory().getPath();
String newFile = p + "/LICENSE.txt";
File nf = new File(newFile); // I want to move file here
if (fileToMove.canWrite()) {
boolean success = fileToMove.renameTo(nf);
if (success == true) {
// LOG to console
Log.i("FILE_MOVED_TO", newFile);
} else {
Log.e("FILE_MOVE_ERROR", tempFileName);
}
} else {
Log.e("PERMISSION_ERROR_TEMP_FILE", tempFileName);
}
}
uploadstatus = UPLOAD_SUCESS;
return new Response("UPLOAD_SUCESS");
} catch (Exception e) {
e.printStackTrace();
uploadstatus = UPLOAD_FAIL;
return new Response("UPLOAD_FAIL");
}
}
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static void copyFile(File src, File dst) throws IOException
{
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
private Response getFullResponse(String mimeType,String filePath) throws FileNotFoundException {
// cleanupStreams();
fileInputStream = new FileInputStream(filePath);
return new Response(Response.Status.OK, mimeType, fileInputStream);
}
private Response getPartialResponse(String mimeType, String rangeHeader,String filePath) throws IOException {
File file = new File(filePath);
String rangeValue = rangeHeader.trim().substring("bytes=".length());
long fileLength = file.length();
long start, end;
if (rangeValue.startsWith("-")) {
end = fileLength - 1;
start = fileLength - 1
- Long.parseLong(rangeValue.substring("-".length()));
} else {
String[] range = rangeValue.split("-");
start = Long.parseLong(range[0]);
end = range.length > 1 ? Long.parseLong(range[1])
: fileLength - 1;
}
if (end > fileLength - 1) {
end = fileLength - 1;
}
if (start <= end) {
long contentLength = end - start + 1;
// cleanupStreams();
fileInputStream = new FileInputStream(file);
//noinspection ResultOfMethodCallIgnored
fileInputStream.skip(start);
Response response = new Response(Response.Status.PARTIAL_CONTENT, mimeType, fileInputStream);
response.addHeader("Content-Length", contentLength + "");
response.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
response.addHeader("Content-Type", mimeType);
return response;
} else {
return new Response(Response.Status.RANGE_NOT_SATISFIABLE, "text/html", rangeHeader);
}
}
int UPLOAD_SUCESS = 1;
int UPLOAD_FAIL = -1;
int UPLOAD_NO = 0;
int uploadstatus;
boolean isfilesOnly;
String filesOnly = "?filesOnly=1";
ArrayList<CLocalFile> list;
StringBuilder sb;
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
// checking if it is a directory
if (listFile[i].isDirectory()) {
if (isfilesOnly)
walkdir(listFile[i]);
else {
CLocalFile f = new CLocalFile();
f.setName(listFile[i].getName());
f.setData(listFile[i].getAbsolutePath());
f.setSize("Folder");
list.add(f);
continue;
}
}
// checking the file extension if it is a file
String fileName = listFile[i].getName();
String extension = "";
int e = fileName.lastIndexOf('.');
if (e > 0) {
extension = fileName.substring(e + 1);
}
if (!isfilesOnly
|| CollabUtility.video_pattern.contains(extension
.toLowerCase(Locale.ENGLISH))
|| CollabUtility.document_pattern.contains(extension
.toLowerCase(Locale.ENGLISH))
|| CollabUtility.audio_pattern.contains(extension
.toLowerCase(Locale.ENGLISH))) {
CLocalFile f = new CLocalFile();
f.setName(fileName);
String mb = "Bytes";
double size = listFile[i].length();
if (size > 1024) {
size = size / 1024;
mb = "KB";
}
if (size > 1024) {
size = size / 1024;
mb = "MB";
}
if (size > 1024) {
size = size / 1024;
mb = "GB";
}
size = Math.floor(size * 100 + 0.5) / 100;
f.setSize(size + " " + mb);
f.setData(listFile[i].getAbsolutePath());
list.add(f);
}
}
}
}
void listofMedia(File file) {
list = new ArrayList<CLocalFile>();
walkdir(file);
// now create the html page
String style = "<style>" + "html {background-color:#eeeeee;} "
+ "body { background-color:#FFFFFF; "
+ "font-family:Tahoma,Arial,Helvetica,sans-serif; "
+ "font-size:18x; " + "border:3px " + "groove #006600; "
+ "padding:15px; } " + "</style>";
String script = "<script language='javascript'>"
+ "function clickit(state) {"
+ "if(state==true){document.getElementById('filesonly').checked="
+ "! document.getElementById('filesonly').checked}"
+ "if ( document.getElementById('filesonly').checked == false ){"
+ "var l=window.location.href;" + "l=l.replace('" + filesOnly
+ "', '');" + "window.location=l;" + "}"
+ "else{var l=window.location.href;"
+ "window.location=String.concat(l,'" + filesOnly + "')" + "}"
+ "}</script>";
Log.d("check", script);
sb = new StringBuilder();
sb.append("<html>");
sb.append("<head>");
sb.append("<title>Files from device</title>");
sb.append(style);
// sb.append("<script language='javascript'>"
// + "function clickit() {"
// + "if ( document.getElementById('filesonly').checked == false ){"
// + "var l=window.location.href;" + "l=l.replace('" + filesOnly
// + "', '');" + "window.location=l;" + "}"
// + "else{var l=window.location.href;"
// + "window.location=String.concat(l,'" + filesOnly + "')" + "}"
// + "}</script>");
sb.append(script);
sb.append("</head>");
sb.append("<body alink=\"blue\" vlink=\"blue\">");
Log.d("check", sb.toString());
// if(true)
// return;
// form upload
sb.append("<h3>File Upload:</h3>");
sb.append("Select a file to upload: <br/>");
sb.append("<form action=\"\" method=\"post\" enctype=\"multipart/form-data\">");
sb.append("<input type=\"file\" name=\"uploadfile\" size=\"50\" />");
sb.append("<input type=\"submit\" value=\"Upload File\" />");
sb.append("</form>");
if (uploadstatus == UPLOAD_FAIL)
sb.append("<h3><font color='red'>The upload was failed</font></h3>");
else if (uploadstatus == UPLOAD_SUCESS)
sb.append("<h3><font color='red'>The upload was successfull</font></h3>");
// if files are there or not
if (list != null && list.size() != 0) {
sb.append("<h3>The following files are hosted live from ");
if (!isfilesOnly)
sb.append("<font color='blue'>" + file.getName()
+ "</font> folder of ");
sb.append("the device</h3>");
} else {
sb.append("<h3>Couldn't find any file from <font color='blue'>"
+ file.getName() + "</font> folder of the device</h3>");
}
// checkbox
if (isfilesOnly)
sb.append("<input type=\"checkbox\" onchange='clickit(false);' checked='true' id=\"filesonly\" />"
+ "<asd onclick='clickit(true);' style=\"cursor:default;\">"
+ "Show only relevant Files (Audio, Video and Documents)</asd>");
else
sb.append("<input type=\"checkbox\" onchange='clickit(false);' id=\"filesonly\" />"
+ "<asd onclick='clickit(true);' style=\"cursor:default;\">"
+ "Show only relevant Files (Audio, Video and Documents)</asd>");
// table of files
sb.append("<table cellpadding='5px' align=''>");
// showing path URLs if not only files
if (!isfilesOnly) {
ArrayList<File> href = new ArrayList<File>();
File parent = new File(file.getPath());
while (parent != null) {
href.add(parent);
// pointing to the next parent
parent = parent.getParentFile();
}
sb.append("<tr>");
sb.append("<td colspan=2><b>");
sb.append("<a href='" + file.getParent() + "'>");
sb.append("UP");
sb.append("</a>");
// printing the whole structure
String path = "";
for (int i = href.size() - 2; i >= 0; --i) {
path = href.get(i).getPath();
if (isfilesOnly)
path += filesOnly;
sb.append(" => <a href='" + path + "'>");
sb.append(href.get(i).getName());
sb.append("</a>");
}
sb.append("</b></td>");
sb.append("</tr>");
}
sb.append("<tr>");
sb.append("<td>");
sb.append("<b>File Name</b>");
sb.append("</td>");
sb.append("<td>");
sb.append("<b>Size / Type</b>");
sb.append("</td>");
sb.append("<tr>");
// sorting the list
Collections.sort(list);
// showing the list of files
for (CLocalFile f : list) {
String data = f.getData();
if (isfilesOnly)
data += filesOnly;
sb.append("<tr>");
sb.append("<td>");
sb.append("<a href='" + data + "'>");
sb.append(f.getName());
sb.append("</a>");
sb.append("</td>");
sb.append("<td align=\"right\">");
sb.append(f.getSize());
sb.append("</td>");
sb.append("</tr>");
}
sb.append("</table>");
sb.append("</body>");
sb.append("</html>");
}
private static class ExampleManagerFactory implements TempFileManagerFactory {
#Override
public TempFileManager create() {
return new ExampleManager();
}
}
private static class ExampleManager implements TempFileManager {
private final String tmpdir;
private final List<TempFile> tempFiles;
private ExampleManager() {
tmpdir = System.getProperty("java.io.tmpdir");
// tmpdir = System.getProperty("/sdcard");
tempFiles = new ArrayList<TempFile>();
}
#Override
public TempFile createTempFile() throws Exception {
DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
tempFiles.add(tempFile);
System.out.println("Created tempFile: " + tempFile.getName());
return tempFile;
}
#Override
public void clear() {
if (!tempFiles.isEmpty()) {
System.out.println("Cleaning up:");
}
for (TempFile file : tempFiles) {
try {
System.out.println(" "+file.getName());
file.delete();
} catch (Exception ignored) {}
}
tempFiles.clear();
}
}
}
If you are using NanoHTTPD r.2.1.0, please try these codes:
#Override
public Response serve(IHTTPSession session) {
Map<String, String> headers = session.getHeaders();
Map<String, String> parms = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
Map<String, String> files = new HashMap<>();
if (Method.POST.equals(method) || Method.PUT.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return getResponse("Internal Error IO Exception: " + ioe.getMessage());
} catch (ResponseException re) {
return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
if ("/uploadfile".equalsIgnoreCase(uri)) {
String filename = parms.get("filename");
String tmpFilePath = files.get("filename");
if (null == filename || null == tmpFilePath) {
// Response for invalid parameters
}
File dst = new File(mCurrentDir, filename);
if (dst.exists()) {
// Response for confirm to overwrite
}
File src = new File(tmpFilePath);
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[65536];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ioe) {
// Response for failed
}
// Response for success
}
// Others...
}
In order to upload multiple files in a single input file like:
<input type="file" name="filename" multiple>
I modify decodeMultipartData() method in NanoHTTPD.java from:
private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
Map<String, String> files) throws ResponseException {
try {
int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while (mpline != null) {
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
}
boundarycount++;
Map<String, String> item = new HashMap<String, String>();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
int p = mpline.indexOf(':');
if (p != -1) {
item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
}
mpline = in.readLine();
}
if (mpline != null) {
String contentDisposition = item.get("content-disposition");
if (contentDisposition == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
}
StringTokenizer st = new StringTokenizer(contentDisposition, ";");
Map<String, String> disposition = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
int p = token.indexOf('=');
if (p != -1) {
disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
}
}
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
String value = "";
if (item.get("content-type") == null) {
while (mpline != null && !mpline.contains(boundary)) {
mpline = in.readLine();
if (mpline != null) {
int d = mpline.indexOf(boundary);
if (d == -1) {
value += mpline;
} else {
value += mpline.substring(0, d - 2);
}
}
}
} else {
if (boundarycount > bpositions.length) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
}
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
do {
mpline = in.readLine();
} while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname, value);
}
}
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
tobe:
private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
Map<String, String> files) throws ResponseException {
try {
String pname_0 = "";
String pname_1 = "";
int pcount = 1;
int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while (mpline != null) {
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
}
boundarycount++;
Map<String, String> item = new HashMap<String, String>();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
int p = mpline.indexOf(':');
if (p != -1) {
item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
}
mpline = in.readLine();
}
if (mpline != null) {
String contentDisposition = item.get("content-disposition");
if (contentDisposition == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
}
StringTokenizer st = new StringTokenizer(contentDisposition, ";");
Map<String, String> disposition = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
int p = token.indexOf('=');
if (p != -1) {
disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
}
}
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
if (pname.contentEquals(pname_0)) {
pname_1 = pname + String.valueOf(pcount);
pcount++;
} else {
pname_0 = pname;
pname_1 = pname;
}
String value = "";
if (item.get("content-type") == null) {
while (mpline != null && !mpline.contains(boundary)) {
mpline = in.readLine();
if (mpline != null) {
int d = mpline.indexOf(boundary);
if (d == -1) {
value += mpline;
} else {
value += mpline.substring(0, d - 2);
}
}
}
} else {
if (boundarycount > bpositions.length) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
}
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname_1, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
do {
mpline = in.readLine();
} while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname_1, value);
}
}
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
Hope this help and sorry for my bad English..:-)
Here's my working code:
public Response serve(IHTTPSession session) {
Map<String, String> headers = session.getHeaders();
Map<String, String> parms = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
Map<String, String> files = new HashMap<>();
if (Method.POST.equals(method) || Method.PUT.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return getResponse("Internal Error IO Exception: " + ioe.getMessage());
} catch (ResponseException re) {
return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
uri = uri.trim().replace(File.separatorChar, '/');
if (uri.indexOf('?') >= 0) {
uri = uri.substring(0, uri.indexOf('?'));
}
// Other implementation goes here...
if ("/uploadfiles".equalsIgnoreCase(uri)) {
String filename, tmpFilePath;
File src, dst;
for (Map.Entry entry : parms.entrySet()) {
if (entry.getKey().toString().substring(0, 8).equalsIgnoreCase("filename")) {
filename = entry.getValue().toString();
tmpFilePath = files.get(entry.getKey().toString());
dst = new File(mCurrentDir, filename);
if (dst.exists()) {
return getResponse("Internal Error: File already exist");
}
src = new File(tmpFilePath);
if (! copyFile(src, dst)) {
return getResponse("Internal Error: Uploading failed");
}
}
}
return getResponse("Success");
}
return getResponse("Error 404: File not found");
}
private boolean deleteFile(File target) {
if (target.isDirectory()) {
for (File child : target.listFiles()) {
if (! deleteFile(child)) {
return false;
}
}
}
return target.delete();
}
private boolean copyFile(File source, File target) {
if (source.isDirectory()) {
if (! target.exists()) {
if (! target.mkdir()) {
return false;
}
}
String[] children = source.list();
for (int i = 0; i < source.listFiles().length; i++) {
if (! copyFile(new File(source, children[i]), new File(target, children[i]))) {
return false;
}
}
} else {
try {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
byte[] buf = new byte[65536];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ioe) {
return false;
}
}
return true;
}
private Response getResponse(String message) {
return createResponse(Response.Status.OK, MIME_PLAINTEXT, message);
}
// Announce that the file server accepts partial content requests
private Response createResponse(Response.Status status, String mimeType, String message) {
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
To allow multiple file upload:
<input type="file" name="filename" multiple>
The same issue existed in the 2.2.1 branch. Following the same logic, I fixed the same function with a few lines of code change.
Add a counter pcount at the beginning of the function:
private void decodeMultipartFormData(String boundary, String encoding, ByteBuffer fbuf, Map<String, String> parms, Map<String, String> files) throws ResponseException {
int pcount = 1;
try {
Then use the counter to update the keyname if filename is not empty:
while (matcher.find()) {
String key = matcher.group(1);
if ("name".equalsIgnoreCase(key)) {
part_name = matcher.group(2);
} else if ("filename".equalsIgnoreCase(key)) {
file_name = matcher.group(2);
// add these two line to support multiple
// files uploaded using the same field Id
if (!file_name.isEmpty()) {
if (pcount > 0)
part_name = part_name + String.valueOf(pcount++);
else
pcount++;
}
}
}
Maybe late, but just for latecommers just like me.
Explained before, the client use okhttp upload a file just like the follow code:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
//sourceFile is a File as you know
.addFormDataPart("image_file_1", "logo-square1.png", RequestBody.create(MediaType.parse("image/png"), sourceFile))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
The follow code is what you want
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
// ▼ 1、parse post body ▼
Map<String, String> files = new HashMap<>();
if (Method.POST.equals(method) || Method.PUT.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return getResponse("Internal Error IO Exception: " + ioe.getMessage());
} catch (ResponseException re) {
return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
//after the body parsed, by default nanoHTTPD will save the file to cache and put it into params( "image_file_1" as key and the value is "logo-square1.png");
//files key is just like "image_file_1", and the value is nanoHTTPD's template file path in cache
// ▲ 1、parse post body ▲
// ▼ 2、copy file to target path xiaoyee ▼
Map<String, String> params = session.getParms();
for (Map.Entry<String, String> entry : params.entrySet()) {
final String paramsKey = entry.getKey();
if (paramsKey.contains("image_file_1")) {
final String tmpFilePath = files.get(paramsKey);
final String fileName = paramsKey;
final File tmpFile = new File(tmpFilePath);
final File targetFile = new File(mCurrentDir + fileName);
LogUtil.log("copy file now, source file path: %s,target file path:%s", tmpFile.getAbsoluteFile(), targetFile.getAbsoluteFile());
//a copy file method just what you like
copyFile(tmpFile, targetFile);
//maybe you should put the follow code out
return getResponse("Success");
}
}
// ▲ 2、copy file to target path xiaoyee ▲
return getResponse("Error 404: File not found");
}

JSON object is returning -1

I want to store these values to server.
The data which i have to store is complete in the variables.
I should get
{"response":{"result":1,"Message":"Poll Entered Successfully."}}
from server
but getting -1
#Override
protected String doInBackground(String... params) {
String jsonString = null;
HttpURLConnection linkConnection = null;
try {
String squestion = question.getText().toString();
String shashtag = hashTag.getText().toString();
spolltime = polltime.getText().toString();
StringBuilder scat = new StringBuilder();
scat.append("");
scat.append(categoryid);
StringBuilder sid = new StringBuilder();
sid.append("");
sid.append(LoginPage.logid);
//int ipolltime = Integer.parseInt(spolltime);
String equestion = URLEncoder.encode(squestion,"UTF-8");
String ehashtag = URLEncoder.encode(shashtag,"UTF-8");
String ecategory = URLEncoder.encode(scat.toString(),"UTF-8");
String eA = URLEncoder.encode(OptionA.stext,"UTF-8");
String eB = URLEncoder.encode(OptionB.stext,"UTF-8");
String eC = URLEncoder.encode(OptionC.stext,"UTF-8");
String eD = URLEncoder.encode(OptionD.stext,"UTF-8");
String eid = URLEncoder.encode(sid.toString(),"UTF-8");
String epolltime = URLEncoder.encode(spolltime,"UTF-8");
URL linkurl = new URL("http://iipacademy.in/askpoll/pollfeeds.php?user_id="+eid+"&question="+equestion+
"&hashtag="+ehashtag+"&category_id="+ecategory+"&option1="+eA+"&option2="+eB+"&option3="+eC+"&option4="+eD+"" +
"&pollopen="+epolltime+"&optiontype1=texty&optiontype2=texty&optiontype3=texty&optiontype4=texty");
linkConnection = (HttpURLConnection) linkurl.openConnection();
int responseCode = linkConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream linkinStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkinStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (linkConnection != null) {
linkConnection.disconnect();
}
}
//Toast.makeText(getApplicationContext(),jsonString.toString(),
//Toast.LENGTH_LONG).show();
return jsonString;
}
I am not able to find my mistake !
thanks
first of all try to make this call from browser and check for response . there is an extension
on chrome PostMan rest client. please check first. may be you are not getting the response correctly.

NullPointerException on getting data from database

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.

Categories

Resources