Pages

Tuesday, June 2, 2015

SharedPreferences

        static SharedPreferences.Editor editor;
static SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;

public static void SaveData(Context c,String KEY,String Value){

sharedpreferences = c.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
editor.putString(KEY,Value);
editor.commit();


}

public static String getData(Context c,String KEY,String FIX){

sharedpreferences = c.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

return sharedpreferences.getString(KEY, FIX);
}

public static void clearData(Context c,String KEY){
sharedpreferences = c.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
editor.remove(KEY);
editor.commit();


}
public static void clearAllData(Context c){
sharedpreferences = c.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
editor.clear();
editor.commit();


}

Wednesday, September 10, 2014

Multipart Entity


HttpClient httpClient = new DefaultHttpClient();
   HttpPost postRequest = new HttpPost("");
   MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
   try {
 
reqEntity.addPart("profile_id",new StringBody(Session_id));
reqEntity.addPart("file_name", new StringBody("abc"));
reqEntity.addPart("file_type",new StringBody(ext));
reqEntity.addPart("caption",new StringBody(ed.getText().toString()));
reqEntity.addPart("upload_data", new FileBody(new File(pathMaster)));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
 
   postRequest.setEntity(reqEntity);      
   HttpResponse response = null;
try {
response = httpClient.execute(postRequest);

Log.e("Response", ""+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   String sResponse;
   StringBuilder s = new StringBuilder();
   try {
while ((sResponse = reader.readLine()) != null) {
   s = s.append(sResponse);
   Log.e("VIDEO RESPONSE", s.toString());
 
   vd = s.toString();
   JSONObject obj = new JSONObject(vd);
   Status = obj.getString(Constant.STATUS);
   Log.e("aaa", Status);
   pd.dismiss();
 
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Thursday, July 3, 2014

custom listview

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
private int[] colors = new int[] { 0xAAff0000, 0xAAffffff };

public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
return data.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView brand,price;

ImageView logo;
Button btn;

inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View itemView = inflater.inflate(R.layout.test, parent, false);
// Get the position
resultp = data.get(position);

// Locate the TextViews in listview_item.xml
brand = (TextView) itemView.findViewById(R.id.tv_brand1);
price = (TextView) itemView.findViewById(R.id.tv_price11);

logo = (ImageView) itemView.findViewById(R.id.iv_logo11);
btn = (Button) itemView.findViewById(R.id.btn_view);

// Capture position and set results to the TextViews
brand.setText(resultp.get(CountryFragment.Name));

price.setText(resultp.get(CountryFragment.Price));






imageLoader.DisplayImage("http://jbtechnology.in/Krishna_Mobile/Logo/"+resultp.get(CountryFragment.Logo), logo);
// Capture ListView item click




btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, detail.class);

intent.putExtra("Name", resultp.get(CountryFragment.Name));
intent.putExtra("Price", resultp.get(CountryFragment.Price));
intent.putExtra("Logo", "http://jbtechnology.in/Krishna_Mobile/Logo/"+resultp.get(CountryFragment.Logo));
intent.putExtra("Desc", resultp.get(CountryFragment.Desc));



context.startActivity(intent);

}
});

/*int colorPos = position % colors.length;
itemView.setBackgroundColor(colors[colorPos]);*/
return itemView;
}

Monday, June 30, 2014

FB



import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;

public class Activity extends Activity {

private Session.StatusCallback statusCallback = new SessionStatusCallback();
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private ProgressDialog mProgressDialog = null;
private SharedPreferences preferences;
private TextView txtFBName;
private Button txtFBLogin;
private boolean isFacebookLogin;
private String userName,Email,bdate,contact;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

preferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);

Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}

txtFBLogin = (Button) findViewById(R.id.activity_login_btn_fb);
txtFBName = (TextView) findViewById(R.id.textView1);
updateView();
txtFBLogin.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (isFacebookLogin) {
postImage();
//openShareContentDialog(FBpostActivity.this, 0, userName);
} else {
onClickLogin();
}
}
});
}

public void postImage() {
       if (checkPermissions()) {
           Bitmap img = BitmapFactory.decodeResource(getResources(),
                   R.drawable.ic_launcher);
           Request uploadRequest = Request.newUploadPhotoRequest(
                   Session.getActiveSession(), img, new Request.Callback() {
                       @Override
                       public void onCompleted(Response response) {
                           Toast.makeText(FBpostActivity.this,
                                   "Photo uploaded successfully",
                                   Toast.LENGTH_LONG).show();
                       }
                   });
           uploadRequest.executeAsync();
       } else {
           requestPermissions();
       }
   }
public boolean checkPermissions() {
       Session s = Session.getActiveSession();
       if (s != null) {
           return s.getPermissions().contains("publish_actions");
       } else
           return false;
   }

   public void requestPermissions() {
       Session s = Session.getActiveSession();
       if (s != null)
           s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                   this, PERMISSIONS));
   }

private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(PERMISSIONS));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}

private void onClickLogout() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
txtFBName.setText("");
}
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}

private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state, Exception exception) {
getFBUserData(session);
updateView();
}
}

public void openShareContentDialog(Context activity, final int option, String userName) {

final Dialog dialogView = new Dialog(activity);
dialogView.setContentView(R.layout.facebook_dialog);
dialogView.setCancelable(false);
dialogView.setCanceledOnTouchOutside(false);
dialogView.setTitle("Share Message");
final Button btnLogout = (Button) dialogView.findViewById(R.id.facebook_dialog_btnLogout);
final Button btnCancel = (Button) dialogView.findViewById(R.id.facebook_dialog_btnCancel);
final Button btnPost = (Button) dialogView.findViewById(R.id.facebook_dialog_btnPost);
final EditText edDescription = (EditText) dialogView.findViewById(R.id.facebook_dialog_edttext_post);
final TextView txtUserName = (TextView) dialogView.findViewById(R.id.facebook_dialog_txt_username);

if (option == 0) {
txtUserName.setText(userName);
} else if (option == 1) {
txtUserName.setText(userName);
}

/**
* Get the data from dialog's control and share the data on faceBook or
* Twitter according to selectedOption.
*/
btnLogout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
if (option == 0) {
onClickLogout();
} else if (option == 1) {
//\\ shared.shareOnTwitter(edDescription.getText().toString());

}
}
});
btnPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
if (option == 0) {
postStatusUpdate(edDescription.getText().toString().trim());
} else if (option == 1) {
// shared.shareOnTwitter(edDescription.getText().toString());

}
}
});

btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
}
});

dialogView.show();
}

private void updateView() {
preferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
Session session = Session.getActiveSession();

if (session.isOpened()) {
txtFBLogin.setText("Already Login");
isFacebookLogin = true;
final String name = preferences.getString("Name", "");
//final String email = preferences.getString("Email", "");

if (name.equalsIgnoreCase("")) {
} else {
txtFBName.setVisibility(View.VISIBLE);
txtFBName.setText("Hello" + " " + name);
}
} else {
txtFBLogin.setText("Login");
isFacebookLogin = false;
txtFBName.setText("");
txtFBName.setVisibility(View.GONE);
}
}

private void postStatusUpdate(String user) {
if (txtFBName.getText() != null && hasPublishPermission()) {
Log.v("KETAN", "hasPublishPermission" + hasPublishPermission());
final String message = getString(R.string.status_update, user, (new Date().toString()));
Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
@Override
public void onCompleted(Response response) {
Toast.makeText(FBpostActivity.this, message, Toast.LENGTH_LONG).show();
}
});
request.executeAsync();
}
}

private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}

@Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}

@Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}

public void getFBUserData(Session session) {

if (session.isOpened()) {
if (FBpostActivity.this != null) {
mProgressDialog = ProgressDialog.show(FBpostActivity.this, "", "Please Wait...");
}

Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}

String link = user.getLink();
userName = user.getUsername();
Email = user.getFirstName();
bdate = user.getBirthday();


isFacebookLogin = true;

if (link.length() != 0) {
SharedPreferences preferences = FBpostActivity.this.getSharedPreferences(
FBpostActivity.this.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("Link", link);
editor.putString("Name", userName);
editor.commit();
}

if (userName != null && userName.length() > 0) {
txtFBName.setText(userName);

Toast.makeText(getApplicationContext(), ""+userName+Email+bdate, 10).show();
//openShareContentDialog(FBpostActivity.this, 0, userName);
}
}
}
});
}
}

}
 <activity android:name="com.facebook.LoginActivity"
                  android:label="@string/app_name" />
        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id"/>


sqlite image database android

b1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
   Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               startActivityForResult(intent, 0);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
          super.onActivityResult(requestCode, resultCode, data);
       
          if(resultCode == RESULT_OK)
          {
          selectedImage = data.getData();  
          bmImage.setImageURI(selectedImage);
          }
      }

b3 = (Button)findViewById(R.id.add);
b3.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub


                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
           if(c == null) return;            
           c.moveToFirst();
           int columnIndex = c.getColumnIndex( MediaStore.Images.Media.DATA);
           ImagePath = c.getString(columnIndex);
           c.close();
               
                byte byteImage1 [] = null;
                try{
                FileInputStream instream = new FileInputStream(ImagePath);
             BufferedInputStream bif = new BufferedInputStream(instream);
             byteImage1 = new byte[bif.available()];
             bif.read(byteImage1);
           
             Log.d("Byte Value",""+byteImage1.length);
                }catch (IOException e) {

}
                d = h.getWritableDatabase();
                ContentValues cv =new  ContentValues();
                cv.put(h.IMAGE_DATA, byteImage1);
                d.insert(h.IMAGE_TABLE, null,cv);
                d.close();
                Toast.makeText(getApplicationContext(), "Save", 6).show();
             
             
       

}
});




Saturday, June 14, 2014

Update Listview by every 1 minute Android

final Handler handler = new Handler()
handler.postDelayed( new Runnable() {

    @Override
    public void run() {
        adapter.notifyDataSetChanged();
        handler.postDelayed( this, 60 * 1000 );
    }
}, 60 * 1000 );

Friday, June 13, 2014

Sorting Listview in Android



Collections.sort(list, comparator);
ActAdapter adp = new ActAdapter(getParent(), list);
lv.setAdapter(adp);
adp.notifyDataSetChanged();

Change Order of map1 and map2 as per your requirement


Comparator<HashMap<String, String>> comparator = new Comparator<HashMap<String, String>>() {
    @Override
    public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
        return map2.get(CREATED).compareTo(map1.get(CREATED));
    }
};