I made a program which uploads selected videos from the SD card to an ASP.NET server. Now I want to add a progress bar to show the status of the uploading file? Can anyone help me about this issue? I am a bit confused. I tried many ways to display the status but I was not successful.
Thanks for helping.
package com.isoft.uploder;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class VideoUploader extends Activity
{
/** Called when the activity is first created. */
public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button camera =(Button)findViewById(R.id.camera);
Button back= (Button)findViewById(R.id.back1);
Button select=(Button)findViewById(R.id.select);
//Video Çek
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
});
//
//Video Seç
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
openGaleryVideo();
}
});
//
//Geri Dön
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
//
}
//Gallery'i aç
public void openGaleryVideo()
{
Intent intent=new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}
//Dosyayı seç ve yükle
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO) {
Uri videoUri = data.getData();
path= getPath(videoUri);
doFileUpload();
}
}
}
//SD carddan yerini al
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Video.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
//upload et
public void doFileUpload()
{
File file=new File(path);
String urlServer = "http://192.168.10.177/androidweb/default.aspx";
String filename=file.getName();
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlServer);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setFixedLengthStreamingMode((int) file.length());
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("SD-FileName", filename);//This will be the file name
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}//end of while statement
//Tekrar video seçmek için
setContentView(R.layout.end);
//event
Button back2=(Button)findViewById(R.id.back2);
Button select2=(Button)findViewById(R.id.new1);
back2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
select2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
openGaleryVideo();
}
});
//
//int serverResponseCode = connection.getResponseCode();
//String serverResponseMessage = connection.getResponseMessage();
//Log.d("ServerCode",""+serverResponseCode);
//Log.d("serverResponseMessage",""+serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}//end of try body
catch (Exception ex)
{
//ex.printStackTrace();
Log.e("Error: ", ex.getMessage());
}
}
}
I did same kind of work, have a look at to my code,
public class LogUploaderActivity extends Activity
{
private static LogUploaderActivity thisAct = null;
private ButtonListener buttonClickListener = null;
private MyDialogInterfaceListener dListener = null;
private RadioButton rbServer;
private RadioButton rbEmail;
private Button cmdOK;
private Button cmdCancel;
// Progress Bar Variables
private static AlertDialog alertDialog = null;
private static ProgressDialog progressDialog = null;
private int delay = 1000;
private ProgressThread progThread;
private int maxBarValue;
private String[] fileName;
private static File directory = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
thisAct = this;
// directory = Environment.getExternalStorageDirectory();
rbServer = (RadioButton) findViewById( R.id.rdWebServer );
rbEmail = (RadioButton) findViewById( R.id.rdLTLogs );
cmdOK = (Button) findViewById( R.id.cmdOK );
cmdCancel = (Button) findViewById( R.id.cmdCancel );
cmdOK.setOnClickListener(getListener());
cmdCancel.setOnClickListener(getListener());
}
private int readLogList( String filePath )
{
directory = Environment.getExternalStorageDirectory();
// System.out.println ( directory + ConstantCodes.FILE_SEPARATOR + filePath );
File folder = new File( directory + ConstantCodes.FILE_SEPARATOR + filePath );
if ( !folder.exists() )
{
return 0;
}
fileName = folder.list();
return folder.list().length;
}
private String readSingleFile( String filePath, String fileName )
{
try
{
// File directory = Environment.getExternalStorageDirectory();
// System.out.println ( "Dir : " + directory );
System.gc();
File file = new File ( directory + ConstantCodes.FILE_SEPARATOR + filePath , fileName );
BufferedReader br = new BufferedReader ( new FileReader ( file) );
String line;
StringBuffer sb = new StringBuffer();
while ( ( line = br.readLine() ) != null )
{
sb.append(line);
}
// byte[] fileData = sb.toString().trim().getBytes();
// String content = sb.toString().trim();
System.out.println ( "File Size : " + sb.toString().length() );
return sb.toString().trim();
}
catch ( Exception e )
{
System.out.println ( "Error while reading File " + e.toString() );
return null;
}
}
private MyDialogInterfaceListener getDialogListener()
{
if ( dListener == null )
{
dListener = new MyDialogInterfaceListener();
}
return dListener;
}
private ButtonListener getListener()
{
if ( buttonClickListener == null )
{
buttonClickListener = new ButtonListener();
}
return buttonClickListener;
}
private class MyDialogInterfaceListener implements DialogInterface.OnClickListener
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
}
}
private class ButtonListener implements Button.OnClickListener
{
public void onClick ( View view )
{
if ( view == cmdCancel )
{
finish();
}
else if ( view == cmdOK )
{
// First Check which Radio Button is selected
if ( rbServer.isChecked() )
{
try
{
maxBarValue = readLogList( ConstantCodes.APPLICATION_LOG_PATH );
Thread.sleep(1000);
}
catch ( Exception e ) { }
if ( maxBarValue > 0 )
{
progressDialog = new ProgressDialog ( thisAct );
progressDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
progressDialog.setMax(maxBarValue);
progressDialog.setMessage( "Uploading Files" );
progressDialog.show();
progThread = new ProgressThread( handler, ConstantCodes.APPLICATION_LOG_PATH, ConstantCodes.TEXT_FILE_METHOD_NAME );
progThread.start();
}
else
{
alertDialog = new AlertDialog.Builder(thisAct).create();
alertDialog.setTitle( "Error" );
alertDialog.setMessage( "No More Logs to Upload" );
alertDialog.setButton( "OK", getDialogListener());
alertDialog.show();
}
}
else if ( rbEmail.isChecked() )
{
try
{
maxBarValue = readLogList( ConstantCodes.LOCATION_TRACKER_PATH );
Thread.sleep(1000);
}
catch ( Exception e ) { }
if ( maxBarValue > 0 )
{
progressDialog = new ProgressDialog ( thisAct );
progressDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
progressDialog.setMax(maxBarValue);
progressDialog.setMessage( "Uploading Files" );
progressDialog.show();
}
else
{
alertDialog = new AlertDialog.Builder(thisAct).create();
alertDialog.setTitle( "Error" );
alertDialog.setMessage( "No More Logs to Upload" );
alertDialog.setButton( "OK", getDialogListener());
alertDialog.show();
}
progThread = new ProgressThread( handler,ConstantCodes.LOCATION_TRACKER_PATH, ConstantCodes.LOCATION_TRACKER_METHOD_NAME );
progThread.start();
}
else
{
alertDialog = new AlertDialog.Builder(thisAct).create();
alertDialog.setTitle( "Error" );
alertDialog.setMessage( "Please Select Any One Option" );
alertDialog.setButton( "OK", getDialogListener());
alertDialog.show();
}
}
}
}
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= maxBarValue)
{
progressDialog.dismiss();
progThread.setState(ProgressThread.DONE);
}
}
};
private class ProgressThread extends Thread
{
final static int DONE = 0;
final static int RUNNING = 1;
int status;
int total;
String filePath;
String METHOD_NAME;
Handler mHandler;
ProgressThread(Handler h, String filePath,String METHOD_NAME )
{
mHandler = h;
this.filePath = filePath;
this.METHOD_NAME = METHOD_NAME;
}
#Override
public void run()
{
status = RUNNING;
while ( status == RUNNING )
{
try
{
Thread.sleep(delay);
}
catch ( Exception e ) { }
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// if ( total < fileName.length )
{
// System.out.println ( "Uploading File Name : " + fileName[total] );
try
{
// System.out.println ( "Method Name : " + METHOD_NAME );
int response = WebService.fileUpload( METHOD_NAME, fileName[total], readSingleFile( filePath,fileName[total] ) );
System.out.println ( "response " + response );
if ( response == 404 )
{
progressDialog.dismiss();
setState(ProgressThread.DONE);
// Thread.sleep(500);
//
// alertDialog = new AlertDialog.Builder( getActivity() ).create();
// alertDialog.setTitle( "Error" );
// alertDialog.setMessage( "Error While Uploading" );
//// alertDialog.setButton( "OK", getDialogListener());
// alertDialog.show();
}
}
catch ( Exception e )
{
// alertDialog = new AlertDialog.Builder( thisAct ).create();
// alertDialog.setTitle( "Error" );
// alertDialog.setMessage( "Error While Uploading" );
// alertDialog.setButton( "OK", getDialogListener());
// alertDialog.show();
}
}
total++;
}
}
public void setState(int state)
{
status = state;
}
}
public static LogUploaderActivity getActivity()
{
return thisAct;
}
public void onDestroy()
{
super.onDestroy();
}
}
It displays total number of files in the sd cards and uploads them to server one by one and shows the status as 2/20 is uploading in progress dialogbox.
If you intend a progress bar in the notification area, please refer to my answer in: Android: show notification bar on downloading application
Related
I am android developer .I have face issue ANR when multiple image send in background using intent service.I have call service on Resume() method.I have update UI when step by step image upload finish .My all code in service .But i don't understand why my UI hang.I have created ResultReceiver class for Update UI. Please tell me what is wrong i am doing.
public class UploadImageService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private static final String TAG = "UploadImageService";
public static String SHOW_MSG = "showMsg";
public static String SET_IN_ADAPTER = "setData";
public static String UPLOAD_IMAGE = "uploadImage";
public static String RESULT = "result";
private String threadType, toUser, chatThreadId, gcmRegistrationId, openCloseChatWindowType, recipientName, threadTopicName, attachmentID, attachmentType, currentChunks, originalBase64Img, dateTime, classType, loginUserId;
// Declare Web services variable
private MultipartEntity multipartEntityBuilder;
Database database;
Bundle bundle;
ResultReceiver receiver;
public UploadImageService() {
super(UploadImageService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
//initialize database
database = new Database(UploadImageService.this, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
Log.d(TAG, "Service Started!");
receiver = intent.getParcelableExtra("receiver");
try {
bundle = new Bundle();
/* Update UI: upload Service is Running */
//receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
/* new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
}
}).start();*/
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Service Stopping!");
//this.stopSelf();
}
private class UploadThumbImageAsync extends AsyncTask<String, Void, String> {
/*this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing*/
String toUser, comTypeId, threadType, chatThreadId, threadTopicName, chatAttachmentType, chatMessage, thumbBase64AttachmentPath /*original_image*/, loginUserName, recipientName, originalBase64Image, originalFilePath;
#Override
protected void onPreExecute() {
super.onPreExecute();
//showProgressDialog();
}
/*starts the loading of the data in background in doInBackground() method */
#Override
protected String doInBackground(String... params) {
try {
toUser = params[0];
comTypeId = params[1];
threadType = params[2];
chatThreadId = params[3];
threadTopicName = params[4];
chatAttachmentType = params[5];
chatMessage = params[6];
thumbBase64AttachmentPath = params[7];
loginUserName = params[8];
recipientName = params[9];
originalBase64Image = params[10];
originalFilePath = params[11];
String url;
if (!TextUtils.isEmpty(threadType) && threadType.equals(RecentChatList.SIMPLE_TYPE)) {
url = WS.URL.concat(WS.SAVE_CHAT);
} else {
url = WS.URL.concat(WS.GROUP_SAVE_CHAT);
}
Log.e(TAG, "url_" + chatMessage + " = " + url);
String response = HttpClientExecuteMethod.executeMultipartPostMethod(url, multipartEntityBuilder);
//Log.e(TAG, "save_chat_history_response_" + threadType + "_" + chatMessage + " =" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*This method is called after the background computation finishes.
The result of background process in passed in this method as parameters
and now you can dismiss progress dialog
and get the result and display on onPostExecute() method
*/
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// Log.e(TAG, "chatAttachmentType = " + chatAttachmentType);
updateCounter();
if (result != null) {
JSONObject jo = new JSONObject(result);
String success = null;
final int storeLimit = SharedPreference.getLimit(UploadImageService.this);
if (jo.has(WS.SUCCESS)) {
success = jo.getString(WS.SUCCESS);
if (!TextUtils.isEmpty(success) && success.equals("0")) {
return;
}
if (!TextUtils.isEmpty(success) && success.equals("100")) {
callWsSaveChat(chatAttachmentType, chatMessage, thumbBase64AttachmentPath, originalBase64Image, originalFilePath);
updateRecentChatAndThreadList();
return;
}
if (!TextUtils.isEmpty(success) && success.equals("99")) {
updateRecentChatAndThreadList();
return;
}
}
try {
ArrayList<Chat> saveChatArrayList = null;
if (!TextUtils.isEmpty(success) && success.equals("1")) {
saveChatArrayList = new Chat().getChatHistory(UploadImageService.this, result, TAG, "");
// Log.e(TAG, "onPostExecute_saveChatArrayList.size = " + saveChatArrayList);
ArrayList<Chat> chatHistoryWithoutMsgId = database.getWithoutMsgIdChatHistory(chatThreadId, "#");
//Log.e(TAG, "onPostExecute_chatHistoryWithoutMsgId.size = " + chatHistoryWithoutMsgId.size());
if (saveChatArrayList != null && !saveChatArrayList.isEmpty() && saveChatArrayList.size() > 0) {
for (int i = 0; i < saveChatArrayList.size(); i++) {
final Chat apiChat = saveChatArrayList.get(i);
String apiMsg = apiChat.getMessage();
String apiThumb = null;
if (!TextUtils.isEmpty(apiChat.getAttachment_thumb())) {
apiThumb = apiChat.getAttachment_thumb().concat("$");
}
if (chatHistoryWithoutMsgId != null && !chatHistoryWithoutMsgId.isEmpty() && chatHistoryWithoutMsgId.size() > 0) {
for (int j = 0; j < chatHistoryWithoutMsgId.size(); j++) {
Chat dbChat = chatHistoryWithoutMsgId.get(j);
final String db_message = dbChat.getMessage();
final String db_thumb = dbChat.getAttachment_thumb();
if (apiThumb.equals(db_thumb)) {
database.updateChatList(apiChat, result, "#", db_message, db_thumb, loginUserId, toUser, chatThreadId, threadType);
bundle.putString(RESULT, UPLOAD_IMAGE);
receiver.send(STATUS_FINISHED, bundle);
if (!TextUtils.isEmpty(chatAttachmentType) && chatAttachmentType.equals(getResources().getString(R.string.Image))) {
originalBase64Image = getBase64Image(originalFilePath);
}
int subLength = 1024 * 256;
//Log.e(TAG, "upload_subLength = " + subLength);
int index = 0;
int totalChunks = 0;
if (!TextUtils.isEmpty(originalBase64Image)) {
for (int k = 0; index < originalBase64Image.length(); k++) {
index = index + subLength;
totalChunks++;
}
database.insertOriginalUploadImageList(apiChat.getAttachment_id(), totalChunks, 0, originalFilePath, chatThreadId, apiChat.getDt_sender_created(), chatAttachmentType);
// database.deleteAttachmentImageList(originalBase64Image);
database.deleteAttachmentImageList(originalFilePath);
UploadOriginalImageList(apiChat.getAttachment_id());
}
break;
} else {
// Log.e(TAG, "onPostExecute_not_equal_image");
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Util.showAlertDialog(mContext, mContext.getResources().getString(R.string.No_internet_connection_available));
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "error = " + e.getMessage());
}
}
There are many methods to upload more images to the server.. one could be including two libraries: apache-mime4j-0.6.jar and httpmime-4.0.1.jar.. After that create your java main code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}
Now your layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>
<TextView
android:id="#+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
of course, include the internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
And voilà. Anyway i followed this example in my case: http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ try to see there.. There are 4 methods to upload multiple files. See which you like
i am trying to reskin an app ( riddle me that )
wheen typing the response the response begin from left to right
i want it to begin from right to left
the answer is in arabic so it has to be from right to left
this how the answer is typed
i want it to be typed like this
this is my activity.java
package com.gkcrop.riddlemethat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.loopj.android.image.SmartImageView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class TheGame extends Activity {
// Variables
InterstitialAd interstitial;
private Button[] word_btn;
private String lvl = "0";
private String coins = "0";
private String[] chars = { "ا", "ب", "ت", "ث", "د", "ذ", "ر", "ز", "س","ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق", "ك", "م", "ن", "ه","و", "ي", "ة", "ئ" };
private String[] word_array;
private String theWord = "999";
private String resultWord = "";
public Button[] randBtn;
Context mContext;
String TextFile,Ribbon;
TextView txt_ribon,txt_riddle;
Button btn_first,btn_bomb,btn_skip,btn_back,btn_ask;
boolean isLast=false;
StringBuilder sb;
private int winSound;
private int failureSound;
private int clickSound;
SoundPool sounds;
EarnCoin coin;
public TheGame() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
coin=new EarnCoin(getApplicationContext());
initSounds();
mContext=TheGame.this;
sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(getString(R.string.app_name));
txt_ribon=(TextView)findViewById(R.id.txt_ribon);
txt_riddle=(TextView)findViewById(R.id.txt_riddle);
btn_first=(Button)findViewById(R.id.button5);
btn_bomb=(Button)findViewById(R.id.button4);
btn_skip=(Button)findViewById(R.id.button3);
btn_back=(Button)findViewById(R.id.button1);
btn_ask=(Button)findViewById(R.id.button6);
AdView adView = (AdView) this.findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());
// 12 orange buttons where appear letters of the word, and other letters
randBtn = new Button[] { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
Intent intent = getIntent();
lvl = readData().split("\\|")[0];
coins = readData().split("\\|")[1];
if (Integer.parseInt(coins) < 0) {
coins = "0";
}
parseXML(Integer.parseInt(lvl)-1);
if(!isLast)
{
txt_riddle.setText(TextFile);
txt_ribon.setText(Ribbon);
word_array = getWord(theWord);
createWord(word_array.length);
randomChars();
TextView lvl_txt = (TextView) findViewById(R.id.textView2);
lvl_txt.setText(" " + lvl + " ");
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.reset_msg_1));
builder.setMessage(getString(R.string.reset_msg_2));
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TheGame.this.finish();
}
});
builder.setNegativeButton(getString(R.string.reset_title),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeData(getString(R.string.point_give));
dialog.dismiss();
TheGame.this.finish();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
btn_first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
btn_first.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_first_letter)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
word_btn[0].setText(word_array[0].toUpperCase());
word_btn[0].setOnClickListener(null);
for (int i = 0; i < 12; i++) {
if (randBtn[i].getText().equals(
word_array[0].toUpperCase())) {
randBtn[i]
.setVisibility(View.INVISIBLE);
i = 12;
}
}
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.first_letter_msg_3)).setIcon(
R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
builder.setMessage(getString(R.string.first_letter_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.first_letter_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
btn_bomb.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_bomb)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
remove3Chars();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.bomb_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
builder.setMessage(getString(R.string.bomb_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.bomb_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
btn_skip.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_skip)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins)));
finish();
startActivity(getIntent());
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.skip_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
builder.setMessage(getString(R.string.skip_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.skip_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
if (Integer.parseInt(lvl) % Integer.parseInt(getString(R.string.number_of_stage_ad)) == 0) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_intertestial_id));
interstitial.loadAd(new AdRequest.Builder().build());
interstitial.show();
if (!interstitial.isLoaded()) {
AdRequest adRequest1 = new AdRequest.Builder()
.build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest1);
}
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
interstitial.show();
}
});
}
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
btn_ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=SaveBackground();
File imagepath=new File(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagepath));
startActivity(Intent.createChooser(share, "Share Image"));
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void initSounds()
{
setVolumeControlStream(3);
sounds = new SoundPool(4, 3, 0);
winSound = sounds.load(this,R.raw.win, 1);
failureSound = sounds.load(this, R.raw.failure, 1);
clickSound = sounds.load(this, R.raw.click2, 1);
}
private void playSound(int i)
{
if (coin.isSoundEnabled())
{
sounds.play(i, 1.0F, 1.0F, 0, 0, 1.0F);
}
}
// Function that generate black squares, depending on the number of letters
// in the word
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(20);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
// Function that generate random letters + word's leter on orange buttons
private void randomChars() {
for (int i = 0; i < 12; i++) {
randBtn[i].setOnClickListener(randCharClick(randBtn[i]));
Random r = new Random();
int i1 = r.nextInt(25 - 0) + 0;
randBtn[i].setText(chars[i1]);
}
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int x = 0; x < word_array.length; x++) {
int value = list.remove(0);
randBtn[value].setText(word_array[x].toUpperCase());
}
}
// Fuction that clear wrong letter from black squares
private OnClickListener charOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < 12; i++) {
if (randBtn[i].getVisibility() == View.INVISIBLE
&& randBtn[i].getText() == button.getText())
randBtn[i].setVisibility(View.VISIBLE);
}
button.setText("");
}
};
}
// Function for orange buttons
private OnClickListener randCharClick(final Button btn) {
return new View.OnClickListener() {
public void onClick(View v) {
playSound(clickSound);
v.setVisibility(View.INVISIBLE);
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() == "") {
word_btn[i].setText(btn.getText());
i = word_array.length;
}
}
createResult();
}
};
}
// Function that check if the word is correct and showing correct/wrong
// dialog
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord += word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
// Function that transform the word to array
private String[] getWord(String str) {
String[] chars = str.split("");
List<String> selected_chars = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
selected_chars.add(chars[i]);
}
selected_chars.remove(0);
return selected_chars.toArray(new String[selected_chars.size()]);
}
// //Function that showing dialogs: correct, wrong or zooming image
private void showMyDialog(final int type, String bmp) {
final Dialog dialog = new Dialog(TheGame.this, R.style.dialogStyle);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().getDecorView()
.setBackgroundResource(R.drawable.dialog_bg);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
String points = ""
+ ((new Random().nextInt(10 - 3) + 3) + word_array.length);
SmartImageView image = (SmartImageView) dialog
.findViewById(R.id.imageDialog);
Button dialogBtn = (Button) dialog.findViewById(R.id.dialogBtn);
TextView score = (TextView) dialog.findViewById(R.id.points);
if (type == 1) {
playSound(winSound);
image.setImageResource(R.drawable.corect);
dialogBtn.setText(" Continue "); // Next level button
score.setText("+" + points);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins) + Integer.parseInt(points)));
} else if (type == 2) {
playSound(failureSound);
image.setImageResource(R.drawable.gresit);
dialogBtn.setText(" Try Again "); // Try again button, restart
// current level
score.setText("-5");
if (Integer.parseInt(coins) > 0 && Integer.parseInt(coins) <= 5) {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt("0")));
} else {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins) - 5));
}
} else {
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
score.setVisibility(View.GONE);
dialogBtn.setVisibility(View.GONE);
ImageView coinicon = (ImageView) dialog
.findViewById(R.id.dialogIcon);
coinicon.setVisibility(View.GONE);
image.setImageUrl(bmp);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
dialog.show();
dialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type > 0) {
finish();
startActivity(getIntent());
}
dialog.dismiss();
}
});
}
// // Button that open "Share on Facebook" dialog
// fb.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// getBitmapFromView().compress(Bitmap.CompressFormat.PNG, 100,
// stream);
// byte[] byteArray = stream.toByteArray();
//// Intent i = new Intent(TheGame.this, LoginFragment.class);
//// i.putExtra("image", byteArray);
//// i.putExtra("lvl", lvl);
//// startActivity(i);
// dialog.dismiss();
// }
// });
// Function that save all user data. Current level, coins
private void writeData(String dataStr) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
openFileOutput("thewords.dat", Context.MODE_PRIVATE));
outputStreamWriter.write(dataStr);
outputStreamWriter.close();
} catch (IOException e) {
}
}
// Function that read user data
private String readData() {
String ret = "";
try {
InputStream inputStream = openFileInput("thewords.dat");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return ret;
}
// Function that hide 3 orange buttons (letters)
public void remove3Chars() {
Button[] removeBtn = { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
int x = 0;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
while (x != 3) {
int value = list.remove(0);
if (!Arrays.asList(word_array).contains(
removeBtn[value].getText().toString().toUpperCase())) {
removeBtn[value].setVisibility(View.INVISIBLE);
x += 1;
}
}
}
private void parseXML(int i) {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream is = assetManager.open("LevelData.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LevelSAXParserHandler myXMLHandler = new LevelSAXParserHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource(is);
xr.parse(inStream);
ArrayList<Level> cartList = myXMLHandler.getCartList();
if(i>=cartList.size())
{
isLast=true;
}
else
{
Level level=cartList.get(i);
theWord=level.getAnswer();
TextFile=level.getTextId();
Ribbon=level.getRibbon();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String SaveBackground()
{
Bitmap bitmap;
RelativeLayout panelResult = (RelativeLayout) findViewById(R.id.root);
panelResult.invalidate();
panelResult.setDrawingCacheEnabled(true);
panelResult.buildDrawingCache();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int i = displaymetrics.heightPixels;
int j = displaymetrics.widthPixels;
bitmap = Bitmap.createScaledBitmap(Bitmap.createBitmap(panelResult.getDrawingCache()), j, i, true);
panelResult.setDrawingCacheEnabled(false);
String s = null;
File file;
boolean flag;
file = new File(sb.toString());
flag = file.isDirectory();
s = null;
if (flag)
{
}
file.mkdir();
FileOutputStream fileoutputstream1 = null;
s = (new StringBuilder(String.valueOf("guess"))).append("_sound_").append(System.currentTimeMillis()).append(".png").toString();
try {
fileoutputstream1 = new FileOutputStream(new File(file, s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fileoutputstream = fileoutputstream1;
StringBuilder stringbuilder1;
bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fileoutputstream);
stringbuilder1 = new StringBuilder();
stringbuilder1.append(sb.toString()).append(File.separator).append(s);
try {
fileoutputstream.flush();
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""+stringbuilder1;
}
}
You need to enable bidirectional text direction.
As usual click Window > Preferences > General > Globalization > Enable bidirectional support. Don't forget to restart your eclipse for it to take effect.
I want to change direction of typing letter from Left To RIGHT
this is Image of this game
this is image of the game:
http://img11.hostingpics.net/pics/357754Capturedcran20150407103535.png
Normally when i type letter it will be in left case , I want to change it to right case
package com.gkcrop.riddlemethat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.loopj.android.image.SmartImageView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class TheGame extends Activity {
// Variables
InterstitialAd interstitial;
private Button[] word_btn;
private String lvl = "0";
private String coins = "0";
private String[] chars = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
private String[] word_array;
private String theWord = "999";
private String resultWord = "";
public Button[] randBtn;
Context mContext;
String TextFile,Ribbon;
TextView txt_ribon,txt_riddle;
Button btn_first,btn_bomb,btn_skip,btn_back,btn_ask;
boolean isLast=false;
StringBuilder sb;
private int winSound;
private int failureSound;
private int clickSound;
SoundPool sounds;
EarnCoin coin;
public TheGame() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
coin=new EarnCoin(getApplicationContext());
initSounds();
mContext=TheGame.this;
sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(getString(R.string.app_name));
txt_ribon=(TextView)findViewById(R.id.txt_ribon);
txt_riddle=(TextView)findViewById(R.id.txt_riddle);
btn_first=(Button)findViewById(R.id.button5);
btn_bomb=(Button)findViewById(R.id.button4);
btn_skip=(Button)findViewById(R.id.button3);
btn_back=(Button)findViewById(R.id.button1);
btn_ask=(Button)findViewById(R.id.button6);
AdView adView = (AdView) this.findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());
// 12 orange buttons where appear letters of the word, and other letters
randBtn = new Button[] { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
Intent intent = getIntent();
lvl = readData().split("\\|")[0];
coins = readData().split("\\|")[1];
if (Integer.parseInt(coins) < 0) {
coins = "0";
}
parseXML(Integer.parseInt(lvl)-1);
if(!isLast)
{
txt_riddle.setText(TextFile);
txt_ribon.setText(Ribbon);
word_array = getWord(theWord);
createWord(word_array.length);
randomChars();
TextView lvl_txt = (TextView) findViewById(R.id.textView2);
lvl_txt.setText(" " + lvl + " ");
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.reset_msg_1));
builder.setMessage(getString(R.string.reset_msg_2));
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TheGame.this.finish();
}
});
builder.setNegativeButton(getString(R.string.reset_title),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeData(getString(R.string.point_give));
dialog.dismiss();
TheGame.this.finish();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
btn_first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
btn_first.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_first_letter)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
word_btn[0].setText(word_array[0].toUpperCase());
word_btn[0].setOnClickListener(null);
for (int i = 0; i < 12; i++) {
if (randBtn[i].getText().equals(
word_array[0].toUpperCase())) {
randBtn[i]
.setVisibility(View.INVISIBLE);
i = 12;
}
}
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.first_letter_msg_3)).setIcon(
R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
builder.setMessage(getString(R.string.first_letter_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.first_letter_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
btn_bomb.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_bomb)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
remove3Chars();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.bomb_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
builder.setMessage(getString(R.string.bomb_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.bomb_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
btn_skip.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_skip)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins)));
finish();
startActivity(getIntent());
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.skip_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
builder.setMessage(getString(R.string.skip_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.skip_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
if (Integer.parseInt(lvl) % Integer.parseInt(getString(R.string.number_of_stage_ad)) == 0) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_intertestial_id));
interstitial.loadAd(new AdRequest.Builder().build());
interstitial.show();
if (!interstitial.isLoaded()) {
AdRequest adRequest1 = new AdRequest.Builder()
.build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest1);
}
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
interstitial.show();
}
});
}
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
btn_ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=SaveBackground();
File imagepath=new File(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagepath));
startActivity(Intent.createChooser(share, "Share Image"));
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void initSounds()
{
setVolumeControlStream(3);
sounds = new SoundPool(4, 3, 0);
winSound = sounds.load(this,R.raw.win, 1);
failureSound = sounds.load(this, R.raw.failure, 1);
clickSound = sounds.load(this, R.raw.click2, 1);
}
private void playSound(int i)
{
if (coin.isSoundEnabled())
{
sounds.play(i, 1.0F, 1.0F, 0, 0, 1.0F);
}
}
// Function that generate black squares, depending on the number of letters
// in the word
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
// Function that generate random letters + word's leter on orange buttons
private void randomChars() {
for (int i = 0; i < 12; i++) {
randBtn[i].setOnClickListener(randCharClick(randBtn[i]));
Random r = new Random();
int i1 = r.nextInt(25 - 0) + 0;
randBtn[i].setText(chars[i1]);
}
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int x = 0; x < word_array.length; x++) {
int value = list.remove(0);
randBtn[value].setText(word_array[x].toUpperCase());
}
}
// Fuction that clear wrong letter from black squares
private OnClickListener charOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < 12; i++) {
if (randBtn[i].getVisibility() == View.INVISIBLE
&& randBtn[i].getText() == button.getText())
randBtn[i].setVisibility(View.VISIBLE);
}
button.setText("");
}
};
}
// Function for orange buttons
private OnClickListener randCharClick(final Button btn) {
return new View.OnClickListener() {
public void onClick(View v) {
playSound(clickSound);
v.setVisibility(View.INVISIBLE);
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() == "") {
word_btn[i].setText(btn.getText());
i = word_array.length;
}
}
createResult();
}
};
}
// Function that check if the word is correct and showing correct/wrong
// dialog
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord += word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
// Function that transform the word to array
private String[] getWord(String str) {
String[] chars = str.split("");
List<String> selected_chars = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
selected_chars.add(chars[i]);
}
selected_chars.remove(0);
return selected_chars.toArray(new String[selected_chars.size()]);
}
// //Function that showing dialogs: correct, wrong or zooming image
private void showMyDialog(final int type, String bmp) {
final Dialog dialog = new Dialog(TheGame.this, R.style.dialogStyle);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().getDecorView()
.setBackgroundResource(R.drawable.dialog_bg);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
String points = ""
+ ((new Random().nextInt(10 - 3) + 3) + word_array.length);
SmartImageView image = (SmartImageView) dialog
.findViewById(R.id.imageDialog);
Button dialogBtn = (Button) dialog.findViewById(R.id.dialogBtn);
TextView score = (TextView) dialog.findViewById(R.id.points);
if (type == 1) {
playSound(winSound);
image.setImageResource(R.drawable.corect);
dialogBtn.setText(" Continue "); // Next level button
score.setText("+" + points);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins) + Integer.parseInt(points)));
} else if (type == 2) {
playSound(failureSound);
image.setImageResource(R.drawable.gresit);
dialogBtn.setText(" Try Again "); // Try again button, restart
// current level
score.setText("-5");
if (Integer.parseInt(coins) > 0 && Integer.parseInt(coins) <= 5) {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt("0")));
} else {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins) - 5));
}
} else {
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
score.setVisibility(View.GONE);
dialogBtn.setVisibility(View.GONE);
ImageView coinicon = (ImageView) dialog
.findViewById(R.id.dialogIcon);
coinicon.setVisibility(View.GONE);
image.setImageUrl(bmp);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
dialog.show();
dialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type > 0) {
finish();
startActivity(getIntent());
}
dialog.dismiss();
}
});
}
// // Button that open "Share on Facebook" dialog
// fb.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// getBitmapFromView().compress(Bitmap.CompressFormat.PNG, 100,
// stream);
// byte[] byteArray = stream.toByteArray();
//// Intent i = new Intent(TheGame.this, LoginFragment.class);
//// i.putExtra("image", byteArray);
//// i.putExtra("lvl", lvl);
//// startActivity(i);
// dialog.dismiss();
// }
// });
// Function that save all user data. Current level, coins
private void writeData(String dataStr) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
openFileOutput("thewords.dat", Context.MODE_PRIVATE));
outputStreamWriter.write(dataStr);
outputStreamWriter.close();
} catch (IOException e) {
}
}
// Function that read user data
private String readData() {
String ret = "";
try {
InputStream inputStream = openFileInput("thewords.dat");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return ret;
}
// Function that hide 3 orange buttons (letters)
public void remove3Chars() {
Button[] removeBtn = { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
int x = 0;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
while (x != 3) {
int value = list.remove(0);
if (!Arrays.asList(word_array).contains(
removeBtn[value].getText().toString().toUpperCase())) {
removeBtn[value].setVisibility(View.INVISIBLE);
x += 1;
}
}
}
private void parseXML(int i) {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream is = assetManager.open("LevelData.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LevelSAXParserHandler myXMLHandler = new LevelSAXParserHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource(is);
xr.parse(inStream);
ArrayList<Level> cartList = myXMLHandler.getCartList();
if(i>=cartList.size())
{
isLast=true;
}
else
{
Level level=cartList.get(i);
theWord=level.getAnswer();
TextFile=level.getTextId();
Ribbon=level.getRibbon();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String SaveBackground()
{
Bitmap bitmap;
RelativeLayout panelResult = (RelativeLayout) findViewById(R.id.root);
panelResult.invalidate();
panelResult.setDrawingCacheEnabled(true);
panelResult.buildDrawingCache();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int i = displaymetrics.heightPixels;
int j = displaymetrics.widthPixels;
bitmap = Bitmap.createScaledBitmap(Bitmap.createBitmap(panelResult.getDrawingCache()), j, i, true);
panelResult.setDrawingCacheEnabled(false);
String s = null;
File file;
boolean flag;
file = new File(sb.toString());
flag = file.isDirectory();
s = null;
if (flag)
{
}
file.mkdir();
FileOutputStream fileoutputstream1 = null;
s = (new StringBuilder(String.valueOf("guess"))).append("_sound_").append(System.currentTimeMillis()).append(".png").toString();
try {
fileoutputstream1 = new FileOutputStream(new File(file, s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fileoutputstream = fileoutputstream1;
StringBuilder stringbuilder1;
bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fileoutputstream);
stringbuilder1 = new StringBuilder();
stringbuilder1.append(sb.toString()).append(File.separator).append(s);
try {
fileoutputstream.flush();
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""+stringbuilder1;
}
}
I need to prevent against lazy load in my custom list-view. so i found that scrollview onscroll listner are helpfull over there i have tryed it but not getting success to implement this functionality.
Code:
lviewAdapter = new ListViewAdapter(SaxParser2.this, Arr_ActivityName, Arr_AudioScript,Arr_RequestID,Arr_FolderPath,Arr_RequestTo);
lview.setOnScrollListener(SaxParser2.this);
#Override
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
lview.setAdapter(lviewAdapter);
}
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
here is my BaseAdapter
package com.RecordingApp;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Sharedpreferance.GMailSender;
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread,welcomeThread2;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
Button record, stop, play, upload;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
holder.record = (Button) convertView.findViewById(R.id.record);
holder.stop = (Button) convertView.findViewById(R.id.stop);
holder.play = (Button) convertView.findViewById(R.id.play1);
holder.upload = (Button) convertView
.findViewById(R.id.audio_upload);
holder.record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else {
if (b_Flag_Record_or_not == true) {
} else {
try {
holder.record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder(
"/audiometer/shanesh"
+ RequestId[position] + "-"
+ str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Recording Started",
Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
gotoGmail(e);
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
holder.stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if (isplaying2 == true) {
mPlayer2.stop();
isplaying2 = false;
} else {
holder.record.setBackgroundResource(R.drawable.page7_15);
if (flag_stop_position == position) {
b_Flag_Record_or_not = false;
if (start_or_not == true) {
b_play_or_not = false;
recorder.stop();
upload_or_not = true;
start_play = true;
Toast.makeText(context, "Stoped Recording",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,
" Please Start recording ",
Toast.LENGTH_LONG).show();
}
} else {
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
});
holder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String temp = SaxParser2.str_completeORpendingFlag;
if (temp.equalsIgnoreCase("c")) {
try {
final MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(Folderpath[position]);
mPlayer.prepare();
final int welcomeScreenDisplay = mPlayer
.getDuration();
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
isplaying2 = true;
mPlayer.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
isplaying2 = false;
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} catch (Exception e) {
gotoGmail(e);
}
} else if (temp.equalsIgnoreCase("p")) {
try {
if (b_play_or_not == true) {
} else {
String str_useid = RequestTo[position];
java.io.File file = new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/", "shanesh"
+ RequestId[position] + "-" + str_useid
+ ".amr");
if (file.exists()) {
Toast.makeText(context, "Playing",
Toast.LENGTH_LONG).show();
mPlayer2 = new MediaPlayer();
try {
mPlayer2.setDataSource(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[position]
+ "-"
+ str_useid + ".amr");
mPlayer2.prepare();
mPlayer2.start();
isplaying2 = true;
final int welcomeScreenDisplay = mPlayer2
.getDuration();
/**
* create a thread to show splash up to
* splash time
*/
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {mPlayer2.prepare();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
welcomeThread2 = new Thread() {
int wait = 0;
#Override
public void run() {
try {
mPlayer2.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
// frameAnimation_play.stop();
isplaying2 = false;
}
}
};
welcomeThread2.start();
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} else {
Toast.makeText(context, " File Not Found ",
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
glob_position = position;
// String str_useid = RequestTo[position];
if (upload_or_not == true) {
try {
new xyz().execute();
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
return convertView;
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(context);
protected void onPreExecute() {
try {
this.dialog.setMessage("Uploading...Please Wait..");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
this.dialog.show();
// put your code which preload with processDialog
} catch (Exception e) {
gotoGmail(e);
}
}
#Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < 100000; i++) {
}
it.sauronsoftware.ftp4j.FTPClient con = new it.sauronsoftware.ftp4j.FTPClient();
try {
String str_useid = RequestTo[glob_position];
con.connect("URL");
con.login("as", "asdasd");
con.changeDirectory("/rangam/RequestContent/audio");
con.setPassive(true);
con.setType(FTPClient.TYPE_BINARY);
con.upload(new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[glob_position] + "-" + str_useid + ".amr"));
String filename = "/shanesh" + RequestId[glob_position] + "-"
+ str_useid + ".amr";
con.logout();
con.disconnect(true);
String MachineName = Machinelist.str_Machinename;
sendFlagToServer(RequestId[glob_position], filename,
MachineName);
} catch (Exception e) {
gotoGmail(e);
}
return null;
}
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(
context);
alertbox.setTitle("Message");
alertbox.setMessage(":: Uploaded Successfully ::");
alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent_request = new Intent(context,
SaxParser2.class);
intent_request.putExtra("value", Machinelist.str_UIDValue);
intent_request.putExtra("machineName",
Machinelist.str_Machinename);
intent_request.putExtra("captureBack_or_not", 2);
context.startActivity(intent_request);
context.finish();
}
});
alertbox.show();
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
private void sendFlagToServer(String requestID, String filename,
String machineName) {
HttpURLConnection connection;
OutputStreamWriter request = null;
String MachineName = Machinelist.str_Machinename;
URL url = null;
String parameters = "RequestID=" + requestID + "&FileName=" + filename
+ "&MachineName=" + MachineName + "&RequestType=A";
try {
url = new URL(
"URL");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
reader.close();
} catch (Exception e) {
gotoGmail(e);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
try {
context.finish();
} catch (Exception e) {
gotoGmail(e);
}
}
return false;
}
void gotoGmail(Exception e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}
}
Ok,
So first you'll have to define "what is the number of views I'd need to load in order my user not to see that it's lazy loading ?" :
Let's say, you'd want to load 20 rows...
Now in you onscroll, or wherever you want but somewhere like on scroll or Adapter.getView, you'll have to know what is displayed on screen at the moment... Let me explain :
I want to load 20 rows so my user doesn't notice,
I am display 10 of them
and 10 of them are just hidden (not displayed if the guy doesn't scroll).
Now, I wan't to load 10 more when the guy just hit my 15th row
What could be the best way to do that ???
Humm, let's see, trying to find something that returns the (ABSOLUTE) number of the last row displayed on screen - this could be a nice solution.
An otehr solution could be that your 10 or 15th row is the first one displayed on screen ?
etc, etc...
I think stuffs like that should do the trick. ;)
Here is a sample I grabbed from Net. It is loading the items by listening to the Scroll of the ListView . For sample it is loading dates in ListView. After reached the end position it will load next 15 dates. It is Never Ending List . You can modify the adapter to your custom adapter. The concept is:
You have set of data
Loading first n no of items
Set the scroll listener to the listview
If scroll reaches Last Visible Item in Listview , You trigger the worker thread to load additional m no of items.
Notify listview from an UI thread.
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> myListItems;
ArrayAdapter<String> adapter;
//For test data :-)
Calendar d = Calendar.getInstance();
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
//Load the first 15 items
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
//Runnable to load the items
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
myListItems = new ArrayList<String>();
//Get 15 new listitems
for (int i = 0; i < itemsPerPage; i++) {
//Fill the item with some bogus information
myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
// +1 day :-D
d.add(Calendar.DATE, 1);
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
//Since we cant update our UI from a thread this Runnable takes care of that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(myListItems != null && myListItems.size() > 0){
for(int i=0;i<myListItems.size();i++)
adapter.add(myListItems.get(i));
}
//Update the Application title
setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
};
EDIT:
You can get tutorial and full project here
I have used following code for download some files from our internet.
public class SplashDownload extends Activity {
public static final int PROGRESS_DIALOG = 0;
private ProgressDialog mProgressDialog;
private WordDataHelper wordDataHelper;
private ExtraDataHelper extraDataHelper;
// put your file path here
private String filePath = "http://test.com/Assets/";
// put your filename here
private String fileName;
// put your download directory name here
private String downloadDir;
private int wordCounter = 0, extraCounter = 0, counter = 1;
private boolean wordDLOn = true;
private int totalFileNo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashdllayout);
getDownloadList();
}
private void goForward() {
Intent intent = new Intent().setClass(this, LangH.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
private void doNext() {
if (wordDLOn) {
System.out.print("wordDetails update: "
+ wordDetails[wordCounter - 1][0]
+ extraDetails[extraCounter][0] + fileName);
wordDataHelper.updateDLStat(Long
.valueOf(wordDetails[wordCounter - 1][0]));
} else {
System.out.print("extraDetails update: "
+ extraDetails[extraCounter - 1][0] + fileName);
extraDataHelper.updateDLStat(Long
.valueOf(extraDetails[extraCounter - 1][0]));
}
if (wordCounter < wordDetails.length) {
System.out.print("wordCounter: " + wordCounter + "/"
+ wordDetails.length);
startDownload(wordDetails[wordCounter][1]);
wordCounter++;
} else if (extraCounter < extraDetails.length) {
wordDLOn = false;
downloadDir = "LanH/extras";
System.out.print("extraCounter: " + extraCounter + "/"
+ extraDetails.length);
startDownload(extraDetails[extraCounter][1]);
extraCounter++;
} else {
goForward();
}
}
private void getDownloadList() {
// lessons download..........
String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
downloadDir = "LanH/words";
String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};
totalFileNo = extraDetails.length + wordDetails.length;
if (wordDetails.length != 0) {
startDownload(wordDetails[wordCounter]);
wordCounter++;
} else if (extraDetails.length != 0) {
wordDLOn = false;
startDownload(extraDetails[extraCounter]);
extraCounter++;
} else {
goForward();
}
}
private void startDownload(String dlFilename) {
// tv = (TextView) findViewById(R.id.tv1);
fileName = dlFilename;
System.out.print("fileName: " + fileName);
File dir = new File(android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/"
+ downloadDir);
// creates the directory if it doesn't exists
if (dir.exists() == false) {
dir.mkdirs();
}
dir = null;
if (checkNet()) {
if (checkExternalMedia() == true) {
String url = filePath + fileName;
new DownloadFileAsync().execute(url, fileName);
mProgressDialog.setMessage("Downloading file.." + fileName);
} else {
Toast.makeText(getApplicationContext(),
"External Media is NOT readable/writable",
Toast.LENGTH_SHORT).show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
/** Method to check whether external media available and writable. */
private boolean checkExternalMedia() {
boolean stat;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
stat = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
stat = false;
} else {
// Can't read or write
stat = false;
}
return stat;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.." + fileName);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS_DIALOG);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
android.os.Environment.getExternalStorageDirectory()
+ "/" + downloadDir + "/" + aurl[1]);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("DOWNLOAD_TEST", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(PROGRESS_DIALOG);
// tv.append("\n\nFile Download Complete!");
// Button btn = (Button) findViewById(R.id.btn1);
// btn.setVisibility(View.GONE);
// you can call a second intent here to redirect to another screen
doNext();
}
}
private boolean checkNet() {
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// we are connected to a network
connected = true;
} else
connected = false;
return connected;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
The process is running fine. It is reported following crash report:
java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
What is the problem in my code? Is isShowing() check before dismissDialog will solve the prob?
Does your progress dialog actually show up?
Instead of dismissing it you could try using removeDialog(PROGRESS_DIALOG); to have it cleaned up.
See if this thread helps - AlerDialog is not created - java.lang.IllegalArgumentException: Activity#onCreateDialog did not create a dialog for id X
When you do the
mProgressDialog.show();
during
protected Dialog onCreateDialog(int id)
you already set the ID for the Dialog to some random or null value.
So when you call to dismiss it, the Application thinks you are crazy.