I'm using Jsch in my program.
I'd like to display a directory that an user currently working on.
So, instead of displaying uid, I would like to show a directory such as, "[/home/user/abc] <user command input>".
My idea on this is sending pwd after every command from an user and parsing the output. But the problem is that I don't know how to parse it from inputstream. How to determine the input boundary between pwd and a user command?
public class TextFieldStreamer extends InputStream implements ActionListener
{
private JTextField tf;
private String str = null;
private int pos = 0;
private boolean finish = false;
public TextFieldStreamer(JTextField jtf)
{
tf = jtf;
}
public void close()
{
finish = true;
try
{
super.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// gets triggered everytime that "Enter" is pressed on the textfield
public void actionPerformed(ActionEvent e)
{
enterAction();
}
public void enterAction()
{
str = tf.getText();
str += "\n";
pos = 0;
}
#Override
public int read()
{
// test if the available input has reached its end
// and the EOS should be returned
if (str != null && pos == str.length())
{
str = null;
// this is supposed to return -1 on "end of stream"
// but I'm having a hard time locating the constant
return java.io.StreamTokenizer.TT_EOF;
}
while (!finish && (str == null || pos >= str.length()))
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return str.charAt(pos++);
}
}
public class TextAreaOutputStream extends OutputStream
{
JTextArea textArea;
public TextAreaOutputStream(JTextArea textArea)
{
this.textArea = textArea;
}
public void write(int b) throws IOException
{
write(new byte[] { (byte) b }, 0, 1);
}
public void write(byte[] b, int off, int len) throws IOException
{
final String text = new String(b, off, len, "UTF-8");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
textArea.append(text);
}
});
}
}
Related
Hello everyone i am getting the messages of the users in android studio for that i am refreshing the recyclerview every second but the probem is scrolling when i am scrooling the recyclerview to old messages then its not scrooling becouse of the getting data every second can someone please help me in this
bellow is my activity code
public class Message_User_Activity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
content();
Clicks();
}
public void content()
{
getdata();
refresh(100);
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
toolbar_user_name.setText(name);
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
}
below is my adapter code
public class Message_user_Adapter extends RecyclerView.Adapter<Message_user_Adapter.Message_user_Adapter_View_Holder>
{
List<responsemodel> data;
String mmessage_To;
public Message_user_Adapter(List<responsemodel> data, String message_To) {
this.data = data;
this.mmessage_To = message_To;
}
#NonNull
#Override
public Message_user_Adapter_View_Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_messages_layout,parent,false);
return new Message_user_Adapter_View_Holder(view);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull Message_user_Adapter_View_Holder holder, int position) {
String time = calculateTime(data.get(position).getMessage_Time());
if (data.get(position).getMessage_From().equals(mmessage_To))
{
holder.other_user_message_message_layout.setVisibility(View.VISIBLE);
holder.other_user_message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.GONE);
}
else
{
holder.other_user_message_message_layout.setVisibility(View.GONE);
holder.message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
private String calculateTime(String post_time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
long time = sdf.parse(post_time).getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago+"";
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
public int getItemCount() {
return data.size();
}
public String getdata() {
return mmessage_To.toString();
}
class Message_user_Adapter_View_Holder extends RecyclerView.ViewHolder
{
TextView other_user_message_message_layout;
TextView message_message_layout;
CircleImageView toolbar_user_profile;
public Message_user_Adapter_View_Holder(#NonNull View itemView) {
super(itemView);
other_user_message_message_layout = itemView.findViewById(R.id.other_user_message_message_layout);
message_message_layout = itemView.findViewById(R.id.message_message_layout);
}
}
}
According to my simple information
in your getdata() function. you send new data to Message_user_Adapter of RecyclerView every time you receive data from API or whatever you use ,so the data of adapter every second is change to new data ,so the RecyclerView being recreated every second with new data and the scroll will not work
just try to outage this lines from onResponse to the first of getdata():
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
and in its place add this line to notify the adapter about changed data :
adapter.notifyDatasetChanged()
something like this :
private void getdata() {
toolbar_user_name.setText(name);
String Choice = "Get Messages";
List<responsemodel> data = new ArrayList<>();//this line was change
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);//this line was change
messages_Message_user_RecyclerView.setAdapter(adapter);//this line was change
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
data = response.body();
adapter.notifyDatasetChanged()//this line was added
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
I have created a custom jmsListenerContainerFactory and MessageListenerContainer for batch processing. The problem is when I pass my custom container factory in #JmsListener(containerFactory=" customContainerFactoryq1") in the listener file, whatever components that I am autowiring in the class is null. But works fine when
I use containerFactory of type DefaultJmsListenerContainerFactory inside the #JmsListener
annotation
Config class
#EnableJms
#Configuration
public class SpringBatchJmsConfig {
#Bean
public ActiveMQConnectionFactory receiverActiveMQConnectionFactory() {
ActiveMQConnectionFactory activeMQConnectionFactory =
new ActiveMQConnectionFactory();
activeMQConnectionFactory.setBrokerURL("tcp://localhost:61616");
return activeMQConnectionFactory;
}
#Bean(name="customContainerFactoryq1")
public CustomJmsListenerContainerFactory customJmsListenerContainerFactory() {
CustomJmsListenerContainerFactory factory = new CustomJmsListenerContainerFactory();
factory.setConnectionFactory(receiverActiveMQConnectionFactory());
return factory;
}
#Bean(name="defaultContainerFactoryq1")
public DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory() {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(receiverActiveMQConnectionFactory());
return factory;
}
#Bean(name="myCustomJmsTemplateMq1")
public JmsTemplate customJmsTemplateMq1() {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(receiverActiveMQConnectionFactory());
return jmsTemplate;
}
Container
public static final int DEFAULT_BATCH_SIZE = 20;
private int batchSize = DEFAULT_BATCH_SIZE;
public CustomJmsListenerContainer() {i
super();
setSessionTransacted(true);
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
#Override
protected boolean doReceiveAndExecute(Object invoker, Session session, MessageConsumer consumer, TransactionStatus status) throws JMSException {
Connection conToClose = null;
MessageConsumer consumerToClose = null;
Session sessionToClose = null;
try {
Session sessionToUse = session;
MessageConsumer consumerToUse = consumer;
if (sessionToUse == null) {
Connection conToUse = null;
if (sharedConnectionEnabled()) {
conToUse = getSharedConnection();
} else {
conToUse = createConnection();
conToClose = conToUse;
conToUse.start();
}
sessionToUse = createSession(conToUse);
sessionToClose = sessionToUse;
}
if (consumerToUse == null) {
consumerToUse = createListenerConsumer(sessionToUse);
consumerToClose = consumerToUse;
}
List<Message> messages = new ArrayList<Message>();
int count = 0;
Message message = null;
do {
message = receiveMessage(consumerToUse);
if (message != null) {
messages.add(message);
}
}
while ((message != null) && (++count < batchSize));
if (messages.size() > 0) {
try {
doExecuteListener(sessionToUse, messages);
sessionToUse.commit();
} catch (Throwable ex) {
handleListenerException(ex);
if (ex instanceof JMSException) {
throw (JMSException) ex;
}
}
return true;
}
noMessageReceived(invoker, sessionToUse);
return false;
} finally {
JmsUtils.closeMessageConsumer(consumerToClose);
JmsUtils.closeSession(sessionToClose);
ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
}
}
protected void doExecuteListener(Session session, List<Message> messages) throws JMSException {
System.out.println("Message Size inside container:" + messages.size());
if (!isAcceptMessagesWhileStopping() && !isRunning()) {
if (logger.isWarnEnabled()) {
logger.warn("Rejecting received messages because of the listener container "
+ "having been stopped in the meantime: " + messages);
}
rollbackIfNecessary(session);
throw new JMSException("Rejecting received messages as listener container is stopping");
}
MessagingMessageListenerAdapter container = (MessagingMessageListenerAdapter)getMessageListener();
Method method = null;
String method Name = null;
try {
method = container.getClass().getDeclaredMethod("getHandlerMethod");
method.setAccessible(true);
InvocableHandlerMethod methodNameObject = (InvocableHandlerMethod)method.invoke(container);
methodName = methodNameObject.getMethod().getName();
Class.forName("com.demo.jms.SampleListener").getMethod(methodName, List.class)invoke(Class.forName("com.demo.jms.SampleListener").newInstance(), message);
} catch (JMSException ex) {
rollbackOnExceptionIfNecessary(session, ex);
throw ex;
} catch (RuntimeException ex) {
rollbackOnExceptionIfNecessary(session, ex);
throw ex;
} catch (Error err) {
rollbackOnExceptionIfNecessary(session, err);
throw err;
}
}
#Override
protected void validateConfiguration() {
if (batchSize <= 0) {
throw new IllegalArgumentException("Property batchSize must be a value greater than 0");
}
}
public void setSessionTransacted(boolean transacted) {
if (!transacted) {
throw new IllegalArgumentException("Batch Listener requires a transacted Session");
}
super.setSessionTransacted(transacted);
}
}
Container Factory
#Nullable
private Executor taskExecutor;
#Nullable
private PlatformTransactionManager transactionManager;
#Nullable
private Integer cacheLevel;
#Nullable
private String cacheLevelName;
#Nullable
private String concurrency;
#Nullable
private Integer maxMessagesPerTask;
#Nullable
private Long receiveTimeout;
#Nullable
private Long recoveryInterval;
#Nullable
private BackOff backOff;
public CustomJmsListenerContainerFactory() {
}
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setCacheLevel(Integer cacheLevel) {
this.cacheLevel = cacheLevel;
}
public void setCacheLevelName(String cacheLevelName) {
this.cacheLevelName = cacheLevelName;
}
public void setConcurrency(String concurrency) {
this.concurrency = concurrency;
}
public void setMaxMessagesPerTask(Integer maxMessagesPerTask) {
this.maxMessagesPerTask = maxMessagesPerTask;
}
public void setReceiveTimeout(Long receiveTimeout) {
this.receiveTimeout = receiveTimeout;
}
public void setRecoveryInterval(Long recoveryInterval) {
this.recoveryInterval = recoveryInterval;
}
public void setBackOff(BackOff backOff) {
this.backOff = backOff;
}
protected CustomJmsListenerContainer createContainerInstance() {
CustomJmsListenerContainer container =new CustomJmsListenerContainer();
container.setBatchSize(60);
container.setCacheLevel(CustomJmsListenerContainer.CACHE_CONSUMER);
container.setConcurrentConsumers(1);
container.setMaxConcurrentConsumers(1);
return container;
}
protected void initializeContainer(CustomJmsListenerContainer container) {
if (this.taskExecutor != null) {
container.setTaskExecutor(this.taskExecutor);
}
if (this.transactionManager != null) {
container.setTransactionManager(this.transactionManager);
}
if (this.cacheLevel != null) {
container.setCacheLevel(this.cacheLevel);
} else if (this.cacheLevelName != null) {
container.setCacheLevelName(this.cacheLevelName);
}
if (this.concurrency != null) {
container.setConcurrency(this.concurrency);
}
if (this.maxMessagesPerTask != null) {
container.setMaxMessagesPerTask(this.maxMessagesPerTask);
}
if (this.receiveTimeout != null) {
container.setReceiveTimeout(this.receiveTimeout);
}
if (this.backOff != null) {
container.setBackOff(this.backOff);
if (this.recoveryInterval != null) {
this.logger.info("Ignoring recovery interval in DefaultJmsListenerContainerFactory in favor of BackOff");
}
} else if (this.recoveryInterval != null) {
container.setRecoveryInterval(this.recoveryInterval);
}
}
}
Listener
#Component
public class Sample Listener {
#Autowired
#Qualifier("myCustomJmsTemplateMq1")
private JmsTemplate jmsTemplate;
#JmsListener(containerFactory="customContainerFactoryq1", destination="myQueue")
public void getMessages(List<Message> msgs) {
//some logic
}
}
Can someone please help me on this.
All looks good to me; exactly what do you think is wrong?
How do I insert data from MySQL into Gridview on Fragments? I've tried it with a coding method used for Activity. I've changed a lot but it's still wrong. This is my coding:
/**
* A simple {#link Fragment} subclass.
*/
public class Product extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
GridView grid_product;
SwipeRefreshLayout swipe;
List<ProductData> newsList = new ArrayList<ProductData>();
private static final String TAG = Product.class.getSimpleName();
private static String url_list = Server.URL + "news.php?offset=";
private int offSet = 0;
int no;
ProductAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
public Product() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
grid_product = (GridView) view.findViewById(R.id.grid_product);
setProduct();
return view;
}
private void setProduct(){
adapter = new ProductAdapter(getActivity(), newsList);
grid_product.setAdapter(adapter);
grid_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pindah activity
startActivity(new Intent(
getActivity(), DetailActivity.class
));
}
});
I don't know where the mistake is:
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
}
);
grid_product.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callNews(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
#Override
public void onRefresh() {
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
I don't know where the mistake is:
private void callNews(int page){
swipe.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ProductData news = new ProductData();
no = obj.getInt(TAG_NO);
news.addId(obj.getString(TAG_ID));
news.addJudul(obj.getString(TAG_JUDUL));
if (obj.getString(TAG_GAMBAR) != "") {
news.addGambar(obj.getString(TAG_GAMBAR));
}
news.addDatetime(obj.getString(TAG_TGL));
news.addIsi(obj.getString(TAG_ISI));
// adding news to news array
newsList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
Drive REST API + GDAA not able to delete the file.
Gone through this question and comments How to delete a file on google drive using Google Drive Android API but when I use driveid.getResourceId(); to pass as a fileId parameter to old Drive API service.files().delete() method its giving error:
Error Required parameteres must be passed it may lead to Dead Lock
My code:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private GoogleAccountCredential credential;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private static Uri fileUri;
private ContentsResult contentsresult;
private GoogleApiClient mGoogleApiClient;
byte[] buffer;
String EXISTING_FILE_ID = "";
int folderCreated = 0;
SharedPreferences prefs;
ArrayList<String> dbfileid = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
String fdd="";
DriveFolderResult sky;
private DriveId mFolderDriveId;
String isfolder;
SharedPreferences sp;
String Shared="Shared";
String folderid="";
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
int j=0;
String songfileid="";
private static com.google.api.services.drive.Drive service;
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
String realid ="";
#Override
protected void onResume() {
super.onResume();
initDrive();
}
private void initDrive() {
credential = GoogleAccountCredential.usingOAuth2(this,Arrays.asList(DriveScopes.DRIVE.split(",")));
credential.setSelectedAccountName("shivrajp130#gmail.com");
service = getDriveService(credential);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName("shivrajp130#gmail.com")
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error" + e.toString());
}
}
#Override
public void onConnected(Bundle connectionHint) {
showToast("Inside Connected");
sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
showToast("Inside Connected");
createSkyFolder();
}
private void createSkyFolder()
{
// TODO Auto-generated method stub
try
{
showToast("creating Folder");
if(!sp.getString(isfolder, "false").contains("created"))
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().
setTitle("Sky folder").build();
sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
showToast("folder created");
sp.edit().putString(isfolder, "created").commit();
// To store secret ID string of file or folder so that we can later get a DriveId object.
realid = sky.getDriveFolder().getDriveId().encodeToString();
sp.edit().putString(folderid, realid).commit();
showToast("Real== "+realid);
}
DriveId retid = DriveId.decodeFromString(sp.getString(folderid, ""));
DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), retid);
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setTitle("New folder")
.build();
MetadataResult res = folder.updateMetadata(getGoogleApiClient(), changeSet2).await();
showToast("Folder== "+folder.getDriveId().encodeToString());
showToast("folder created");
upladfile();
}
catch(Exception e)
{
showToast(""+e);
}
}
private void upladfile() {
// TODO Auto-generated method stub
String storedId=sp.getString(folderid, "");
DriveId retid = DriveId.decodeFromString(storedId);
DriveFolder skyfolder = Drive.DriveApi.getFolder(getGoogleApiClient(), retid);
contentsresult = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = contentsresult.getContents().getOutputStream();
String s = Environment.getExternalStoragePublicDirectory("Download")
.getPath().toString();
showToast(s);
File file = new File(s + "/k.mp3");
showToast("Path=" + Environment.DIRECTORY_DOWNLOADS + "/k"
+ file.length());
buffer = new byte[(int) file.length()];
try {
showToast("started reading n writing");
outputStream.write(buffer);
showToast("Buffer is written");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast("" + e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast("" + e.toString());
}
showToast("" + contentsresult.getContents().toString());
//DriveFolder fldr = Drive.DriveApi.getFolder(getGoogleApiClient(),sky.getDriveFolder().getDriveId());
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setTitle("New file").setMimeType("audio/MP3").setStarred(true)
.build();
showToast("meta data created");
DriveFileResult fileresult = skyfolder.createFile(getGoogleApiClient(),
changeSet2, contentsresult.getContents()).await();
songfileid = fileresult.getDriveFile().getDriveId().encodeToString();
showToast("file has been created "+fileresult.toString());
// Status stat = Drive.DriveApi.requestSync(mGoogleApiClient).await();
showToast("await() complete");
if (!contentsresult.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
add_to_db();
getvalues();
//String storedId=sp.getString(folderid, "");
DriveId fffid = DriveId.decodeFromString(dbfileid.get(0));
DriveFile fff = Drive.DriveApi.getFile(getGoogleApiClient(), fffid);
MetadataChangeSet changeSet3 = new MetadataChangeSet.Builder()
.setTitle("renamed")
.build();
MetadataResult res = fff.updateMetadata(getGoogleApiClient(), changeSet3).await();
if(res!=null)
{
showToast("renamed"+res.getMetadata().getTitle());
}
try {
//String iid=fffid.getResourceId();
service.files().delete(fffid.getResourceId()).execute();
showToast("Delete");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
public void add_to_db()
{
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
String id =songfileid;
String name="k";
showToast("database id ="+id);
values.put(fileid,id);
values.put(filename,name);
database.insert(TABLE, null, values);
database.close();
Toast.makeText(this,"Added Successfully" ,Toast.LENGTH_LONG).show();
}
public void getvalues()
{
showToast("getting Values");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
dbfileid.add(cursor.getString(0));
dbfilename.add(cursor.getString(1));
showToast("id=="+dbfileid.get(j).toString());
j++;
} while (cursor.moveToNext());
}
}
private com.google.api.services.drive.Drive getDriveService(GoogleAccountCredential credential) {
return new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
#Override
public void onConnectionSuspended(int cause) {
showToast("GoogleApiClient connection suspended");
}
}
Except delete everything is working fine.
service.files().delete(fffid.getResourceId()).execute();
Any REST Api's .execute() (as well as GDAA's .await() flavored calls) must be run off UI thread. You should wrap it in:
new AsyncTask<Void, Void, Void>() {
#Override protected Integer doInBackground(String... params) {
//...
return null;
}
}.execute(); // .cancel(true);
or
new Thread(new Runnable() { #Override public void run() {
//....
}}).start();
Good Luck
I'm struggling with a at the first sight simple problem (and probably it is so...) - I have to disable certain button in the JTable upon value in one of the cells within the same row.
Below is my inner class for button rendering and editing:
private class CellButton {
class ButtonsPanel extends JPanel {
public JButton jbutton = new JButton("Accept!!");
public ButtonsPanel() {
super();
setOpaque(true);
jbutton.setFocusable(false);
jbutton.setRolloverEnabled(false);
jbutton.setSize(122, 30);
jbutton.setFont(new java.awt.Font("Tahoma", 3, 12));
jbutton.setForeground(new java.awt.Color(0, 102, 102));
add(jbutton);
}
private class ButtonsRenderer extends ButtonsPanel implements TableCellRenderer {
ButtonsPanel bp;
public ButtonsRenderer() {
super();
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
Object o = table.getModel().getValueAt(row, 8);
bp = (ButtonsPanel) o;
if (jTable5.getValueAt(row, 3).equals("NORMALNA")) {
bp.jbutton.setEnabled(false);
}
return this;
}
}
private class ButtonsEditor extends ButtonsPanel implements TableCellEditor {
ButtonsPanel bp;
public ButtonsEditor(final JTable table, final String tableName) {
super();
//DEBUG: view button click -> control key down + edit button(same cell) press -> remain selection color
MouseListener ml = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
ButtonModel m = ((JButton) e.getSource()).getModel();
if (m.isPressed() && table.isRowSelected(table.getEditingRow()) && e.isControlDown()) {
setBackground(table.getBackground());
}
}
};
jbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int row = table.convertRowIndexToModel(table.getEditingRow());
Object o = table.getModel().getValueAt(row, 0);
fireEditingStopped();
//update info status
setDmlUpdateStatusPrejeteInfo();
jDialog2.requestFocus();
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
fireEditingStopped();
}
});
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
this.setBackground(table.getSelectionBackground());
Object o = table.getModel().getValueAt(row, 8);
bp = (ButtonsPanel) o;
if (jTable5.getValueAt(row, 3).equals("NORMALNA")) {
bp.jbutton.setEnabled(false);
}
return this;
}
#Override
public Object getCellEditorValue() {
return "";
}
transient protected ChangeEvent changeEvent = null;
#Override
public boolean isCellEditable(EventObject e) {
return true;
}
#Override
public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
#Override
public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
#Override
public void cancelCellEditing() {
fireEditingCanceled();
}
#Override
public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
}
#Override
public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
}
public CellEditorListener[] getCellEditorListeners() {
return listenerList.getListeners(CellEditorListener.class);
}
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent);
}
}
}
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
}
}
}
}
public ButtonsRenderer br() {
return new ButtonsRenderer();
}
public ButtonsEditor be(JTable jTable, String tableName) {
return new ButtonsEditor(jTable, tableName);
}
}
a) it's better not to call a Jbutton in the name Jbutton, it's just confusing
b) there are many way to disable a jbutton (make it disappear, remove it, resize it...) but the best one is probably this:
Jbutton.setEnabled(false);
c) I think you can use this very useful guide: http://www.macs.hw.ac.uk/guidebook/?name=JButton&page=1