Create Offline SQLite DataBase in Android - android

I try to create offline SQLite database for my send job module in android application. but the database in not created in DDMS .Tell me where I am wrong in the given code below.
Fregmentsendjob.java
public class FragmentSendJob extends Fragment implements OnClickListener {
// this Fragment will be called from MainActivity
private Button submit,cancel;
private EditText ename,mobno,picktime,unit,street,suburb,destination,fare,city;
private Spinner state,group;
private ViewGroup vgroup ;
String name,pass;
String status_key;
private Typeface ftype;
private static MyDialog dialog1;
Bitmap bitmap1, bitmap2,bitmap3;
Bitmap[] bitmap;
String[] driver_details;
private byte imageInByte1[],imageInByte2[],imageInByte3[] ;
private Context mContext;
public String advertisement_count;
private String mename,mmobno,mpicktime,munit,mstreet,msuburb,mstate, msendjob,mcity,mdestination,mfare,mgroup,login_token;
// private String sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate, ssendjob,scity,sdestination,sfare,sgroup,login_token;
private static FragmentDialog dialog;
//private SendJobDataBase db;
private PasswordDB db;
static final int DIALOG_ID = 0;
private SharedPreferences pref1,pref;
String latitude,longitude;
public String job_id;
public FragmentSendJob(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.sendjob_fragment, container, false);
pref1=this.getActivity().getSharedPreferences("LocDetails", getActivity().MODE_WORLD_READABLE);
pref=this.getActivity().getSharedPreferences("Driver", getActivity().MODE_WORLD_READABLE);
login_token=pref.getString("login_token","login_token");
latitude = pref1.getString("latitude","latitude");
longitude = pref1.getString("longitude","longitude");
ename = (EditText) rootView.findViewById(R.id.ename);
mobno = (EditText) rootView.findViewById(R.id.mobno);
picktime = (EditText) rootView.findViewById(R.id.picktime);
unit = (EditText) rootView.findViewById(R.id.unit);
street = (EditText) rootView.findViewById(R.id.street);
suburb = (EditText) rootView.findViewById(R.id.suburb);
destination = (EditText) rootView.findViewById(R.id.destination);
state = (Spinner) rootView.findViewById(R.id.state);
fare=(EditText) rootView.findViewById(R.id.fare);
group = (Spinner) rootView.findViewById(R.id.group);
city = (EditText) rootView.findViewById(R.id.city);
vgroup = (ViewGroup) rootView.findViewById(R.id.rel);
submit = (Button) rootView.findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new SendJob().execute();
/* Intent intent =new Intent(getActivity(),GetCurrentLocation.class);
startActivity(intent);
System.out.println(">>>>>>>>>>>>>>>>>"+latitude+"***********");
System.out.println(">>>>>>>>>>>>"+longitude+"***********");*/
}
});
cancel = (Button) rootView.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = 0, count = vgroup.getChildCount(); i < count; ++i) {
View view = vgroup.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
}
}
});
String[] mystate= new String[]{"New South Wales","Victoria","Queensland","Northern Territory","Western Australia","South Australia"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.listrow, mystate);
state.setAdapter(adapter);
state.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) {
// TODO Auto-generated method stub
mcity = state.getSelectedItem().toString();
String s1=arg0.getItemAtPosition(pos).toString();
if(s1.equals("New South Wales"))
city.setText("Sydney");
else if(s1.equals("Victoria"))
city.setText("Melbourne");
else if(s1.equals("Queensland"))
city.setText("Brisbane");
else if(s1.equals("Northern Territory"))
city.setText("Darwin");
else if(s1.equals("Western Australia"))
city.setText("Perth");
else if(s1.equals("South Australia"))
city.setText("Adelaide");
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
String[] mygroups= new String[]{"My Group","My Secondary group","Everyone"};
ArrayAdapter<String> adapters = new ArrayAdapter<String>(this.getActivity(),
R.layout.listrow, mygroups);
group.setAdapter(adapters);
group.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
msendjob = group.getItemAtPosition(pos).toString();
//gender.setText(setgender);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return rootView;
}
private class SendJob extends AsyncTask<String, String, String[]> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
#Override
protected String[] doInBackground(final String... params)
{
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
HttpClient httpclient = new DefaultHttpClient();
try
{
System.out.print("***** login token *****"+login_token);
JSONObject job= new JSONObject();
mename = ename.getText().toString();
mmobno = mobno.getText().toString();
mpicktime = picktime.getText().toString();
munit = unit.getText().toString();
mstreet = street.getText().toString();
msuburb = suburb.getText().toString();
mstate = state.getSelectedItem().toString();
mcity = city.getText().toString();
mdestination = destination.getText().toString();
mgroup = group.getSelectedItem().toString();
mfare = fare.getText().toString();
mename.replace("" ,"%20");
mmobno.replace("" ,"%20");
mpicktime.replace("" ,"%20");
munit.replace("" ,"%20");
mstreet.replace("" ,"%20");
mstate.replace("" ,"%20");
msuburb.replace("" ,"%20");
mcity.replace("" ,"%20");
mdestination.replace("" ,"%20");
mgroup.replace("" ,"%20");
mfare.replace("" ,"%20");
job.put("name",mename);
job.put("mobile_no",mmobno);
job.put("pickup_time",mpicktime);
job.put("unit_no",munit);
job.put("street_name",mstreet);
job.put("state",mstate);
job.put("suburb",msuburb);
job.put("city",mcity);
job.put("destination",mdestination);
job.put("group",mgroup);
job.put("fare",mfare);
job.put("latitude",latitude);
job.put("longitude",longitude);
job.put("status_key","2");
job.put("method","send_job");
job.put("login_token",login_token);
StringEntity se = new StringEntity(job.toString());
HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String data = EntityUtils.toString(response.getEntity());
Log.i("response", data);
System.out.println("response "+data);
String call;
call = data;
System.out.println("print me............."+call);
JSONObject jo = new JSONObject(data);
Log.d("response", jo.toString(4));
/*JSONObject jobId= jo.getJSONObject("id");
job_id=jobId.getString("id");*/
if(jo.getString("err-code").equals("0"))
{
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Alert!!!");
alert.setMessage(jo.getString("message"));
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
pDialog.dismiss();
dialog.dismiss();
/* Intent intent =new Intent(getActivity(),HandleData.class);
intent.putExtra("pickupsuburb", ssuburb);
intent.putExtra("destination", sdestination);
startActivity(intent);*/
}
});
getActivity().runOnUiThread(new Runnable() {
public void run() {
alert.show();
}
});
}
else
{
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Alert !");
alert.setMessage(jo.getString("message"));
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
pDialog.dismiss();
alert.show();
}
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
return params;
}
#Override
protected void onPostExecute(String[] result)
{
super.onPostExecute(result);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
**SendJobDatabase.java**
public class SendJobDataBase
{
private static final String DATABASE_NAME = "SENDJOB.db";
private static final int DATABASE_VERSION = 2;
static final String TABLE_NAME = "jobsend";
private static final String KEY_ID = "id";
private static Context context;
static SQLiteDatabase db;
private final ArrayList<member> user = new ArrayList<member>();
OpenHelper helper;
private SQLiteStatement insertStmt;
//creation of string value and insert that string value into table name
private static final String INSERT = "insert into " + TABLE_NAME + " (mename,mmobno,mpicktime,munit,mstreet,msuburb,mstate,mcity,mdestination,mfare,mgroup) values (?,?,?,?,?,?,?,?,?,?,?)";
// private static final String INSERT = "insert into " + TABLE_NAME + " (sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate,scity,sdestination,sfare,sgroup) values (?,?,?,?,?,?,?,?,?,?,?)";
protected static final String enternpw = null;
public SendJobDataBase(Context context) {
SendJobDataBase.context = context;
OpenHelper openHelper = new OpenHelper(SendJobDataBase.context);
SendJobDataBase.db = openHelper.getWritableDatabase();
this.insertStmt = SendJobDataBase.db.compileStatement(INSERT);
}
//public long insert(String sename,String smobno,String spicktime,String sunit,String sstreet,String ssuburb,String sstate,String scity,String sdestination,String sfare,String sgroup) {
public long insert(String mename,String mmobno,String mpicktime,String munit,String mstreet,String msuburb,String mstate,String mcity,String mdestination,String mfare,String mgroup) {
this.insertStmt.bindString(1, mename);
this.insertStmt.bindString(2, mmobno);
this.insertStmt.bindString(3, mpicktime);
this.insertStmt.bindString(4, munit);
this.insertStmt.bindString(5, mstreet);
this.insertStmt.bindString(6, msuburb);
this.insertStmt.bindString(7, mstate);
this.insertStmt.bindString(8, mcity);
this.insertStmt.bindString(9, mdestination);
this.insertStmt.bindString(10, mfare);
this.insertStmt.bindString(11, mgroup);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
//create a function and apply cursor activity to perform on function
List<String[]> list = new ArrayList<String[]>();
//Cursor cursor = db.query(TABLE_NAME, new String[] { "id","sename","smobno","spicktime","sunit","sstreet","ssuburb","sstate","scity","sdestination","sfare","sgroup" }, null, null, null, null, "sename asc");
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","mename","mmobno","mpicktime","munit","mstreet","msuburb","mstate","mcity","mdestination","mfare","mgroup" }, null, null, null, null, "sename asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5),
cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public ArrayList<member> getMembersList() {
ArrayList<member> user = new ArrayList<member>();
String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%One%'" ;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
user.add(contact);
} while (cursor.moveToNext());
}
}
cursor.close();
return user;
}
public ArrayList<member> getMembersList2() {
ArrayList<member> user = new ArrayList<member>();
String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%Two%'" ;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
user.add(contact);
} while (cursor.moveToNext());
}
}
cursor.close();
return user;
}
public void delete(int rowId) {
db.delete(TABLE_NAME, null, null);
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, sename TEXT, smobno TEXT,spicktime TEXT,spickaddr TEXT, sfair TEXT,ssendjob TEXT)");
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, mename TEXT, mmobno TEXT,mpicktime TEXT,mpickaddr TEXT, mfair TEXT,msendjob TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public Cursor rawQuery(String selectQuery ,Object object) {
// TODO Auto-generated method stub
return null;
}
public static SendJobDataBase getDBAdapterInstance(FragmentGroups viewPassword) {
// TODO Auto-generated method stub
return null;
}
public Object getenternpw() {
// TODO Auto-generated method stub
return null;
}
public static Cursor getSinlgeEntry() {
// TODO Auto-generated method stub
Cursor cur =db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
// colName1+"='"+name+"'" -> wherclause
System.out.println("Record count are "+cur.getCount());
return cur;
}
static public void close() {
// TODO Auto-generated method stub
}
/* public SendJobDataBase open() throws SQLException {
// TODO Auto-generated method stub
db = helper.getWritableDatabase();
return this;
} */
public SendJobDataBase getWritableDatabase() {
// TODO Auto-generated method stub
return null;
}
public void Delete_Contact(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
public ArrayList<member> Get_Contacts() {
try {
user.clear();
// Select All Query
String selectQuery = "SELECT * FROM jobsend";
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
// contact.setPhoneNumber(cursor.getString(2));
// contact.setEmail(cursor.getString(3));
// Adding contact to list
user.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return user;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return user;
}
}

implementation 'com.intuit.sdp:sdp-android:1.0.4'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.android.support:recyclerview-v7:28.0.0'
activity_main.xml
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recyclerviiew_main"
android:layout_height="match_parent"/>
raw_innerview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:paddingLeft="1dp"
android:orientation="vertical"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:background="#color/colorAccent"
android:id="#+id/txt_Title"
android:layout_width="#dimen/_100sdp"
android:gravity="center"
android:layout_height="#dimen/_100sdp"
android:layout_marginTop="4dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
tools:text="More" />
</LinearLayout>
</LinearLayout>
raw_mailn_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:paddingLeft="1dp"
android:orientation="vertical"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
tools:text="Name" />
<TextView
android:id="#+id/txt_Title1"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
tools:text="More" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recyclerview_inner"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.app.playstorerecyclerviewdemo.model.InnerData;
import com.app.playstorerecyclerviewdemo.model.MainResponse;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
List arry_favorite =new ArrayList();
List arry_song =new ArrayList();
List arry_mostview=new ArrayList();
List arry_name =new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arry_favorite.add("1");
arry_favorite.add("2");
arry_favorite.add("3");
arry_favorite.add("4");
arry_song.add("1");
arry_song.add("2");
arry_song.add("3");
arry_song.add("4");
arry_song.add("5");
arry_song.add("6");
arry_song.add("7");
arry_mostview.add("1");
arry_mostview.add("5");
arry_mostview.add("6");
arry_name.add("Songs");
arry_name.add("Mostviews");
arry_name.add("Favourits");
InnerData datum=new InnerData();
MainResponse example=new MainResponse();
example.setStatus("true");
example.setMessage("Data is Display");
datum.setName("Title");
datum.setStatusMore("More");
datum.setFavorites(arry_favorite);
datum.setSongs(arry_song);
datum.setMostviewes(arry_mostview);
example.setData(datum);
Log.e("JSONS",new Gson().toJson(datum.toString()));
if(example.getStatus().equalsIgnoreCase("true"))
{
RecyclerView recyclerview=findViewById(R.id.recyclerviiew_main);
Toast.makeText(this, example.getMessage(), Toast.LENGTH_SHORT).show();
MainViewAdapter adapter = new MainViewAdapter(MainActivity.this, datum);
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
recyclerview.setLayoutManager(gridLayoutManager);
recyclerview.setAdapter(adapter);
}
else {
Toast.makeText(this, example.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
MainViewAdapter.java
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.app.playstorerecyclerviewdemo.model.InnerData;
public class MainViewAdapter extends RecyclerView.Adapter<MainViewAdapter.ViewHolder> {
public Context context;
public InnerData arraylist;
public MainViewAdapter(MainActivity listdata, InnerData arraylist)
{
this.context = listdata;
this.arraylist = arraylist;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.raw_mailn_view, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
if(arraylist.getName() !=null)
{
holder.txt_Title.setText(arraylist.getName());
}
if(arraylist.getStatusMore() !=null)
{
holder.txt_Title1.setText(arraylist.getStatusMore());
}
InnerViewAdapter adapter = new InnerViewAdapter((MainActivity) context, arraylist);
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
holder.recyclerview_inner.setLayoutManager(gridLayoutManager);
holder.recyclerview_inner.setAdapter(adapter);
}
#Override
public int getItemCount() {
return 10;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_Title,txt_Title1;
RecyclerView recyclerview_inner;
public ViewHolder(View itemView) {
super(itemView);
txt_Title = itemView.findViewById(R.id.txt_Title);
txt_Title1 = itemView.findViewById(R.id.txt_Title1);
recyclerview_inner=itemView.findViewById(R.id.recyclerview_inner);
}
}
}
InnerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.app.playstorerecyclerviewdemo.model.InnerData;
class InnerViewAdapter extends RecyclerView.Adapter<InnerViewAdapter.ViewHolder>
{
public Context context;
public InnerData arraylist;
public InnerViewAdapter(MainActivity listdata, InnerData arraylist)
{
this.context = listdata;
this.arraylist = arraylist;
}
#Override
public InnerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.raw_innerview, parent, false);
InnerViewAdapter.ViewHolder viewHolder = new InnerViewAdapter.ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(final InnerViewAdapter.ViewHolder holder, final int position)
{
if(arraylist.getSongs() !=null)
{
holder.txt_Title.setText(arraylist.getName());
holder.txt_Title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, ""+position, Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public int getItemCount() {
return 3;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_Title;
public ViewHolder(View itemView) {
super(itemView);
txt_Title = itemView.findViewById(R.id.txt_Title);
}
}
}
MainResponse.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MainResponse {
#SerializedName("status")
#Expose
private String status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
public InnerData data = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public InnerData getData() {
return data;
}
public void setData(InnerData data) {
this.data = data;
}
}
InnerData.java
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class InnerData {
#SerializedName("name")
#Expose
private String name;
#SerializedName("status_more")
#Expose
private String statusMore;
#SerializedName("songs")
#Expose
private List<Integer> songs = null;
#SerializedName("favorites")
#Expose
private List<Integer> favorites = null;
#SerializedName("mostviewes")
#Expose
private List<Integer> mostviewes = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatusMore() {
return statusMore;
}
public void setStatusMore(String statusMore) {
this.statusMore = statusMore;
}
public List<Integer> getSongs() {
return songs;
}
public void setSongs(List<Integer> songs) {
this.songs = songs;
}
public List<Integer> getFavorites() {
return favorites;
}
public void setFavorites(List<Integer> favorites) {
this.favorites = favorites;
}
public List<Integer> getMostviewes() {
return mostviewes;
}
public void setMostviewes(List<Integer> mostviewes) {
this.mostviewes = mostviewes;
}
}
Utility.scheduleJob(this, startLatitude, startLongitude, latitude, longitude);
#SuppressLint("NewApi")
#RequiresApi(api = Build.VERSION_CODES.M)
public static void scheduleJob(Context context, double startLatitude, double startLongitude, double latitude, Double longitude) {
ComponentName serviceComponent = new ComponentName(context, CalculateKmService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(10 * 1000); // wait at least 10 sec
builder.setOverrideDeadline(5 * 1000); // maximum delay
//builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
//builder.setRequiresDeviceIdle(true); // device should be idle
//builder.setRequiresCharging(false); // we don't care if the device is charging or not
jobScheduler = (JobScheduler) getContext().getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
Log.d("TAG", "scheduleJob:....... " + startLatitude + "....." + latitude);
Log.d("TAG", "scheduleJob:.......... " + startLongitude + "....." + longitude);
// startLatitude=23.072018;
// startLongitude=72.542134;
try {
// GoogleMatrixRequest.calculateKm(context, startLatitude, startLongitude, latitude, longitude);
if(FastSave.getInstance().getString(Constant.END_LAT_1).equals(""))
{
try
{
Log.d("TAG", "scheduleJob: from start");
GoogleMatrixRequest.calculateKm(context, startLatitude, startLongitude, latitude, longitude);
} catch (Exception e) {
e.printStackTrace();
}
}else{
double last_lat = Double.parseDouble(FastSave.getInstance().getString(Constant.END_LAT_1));
double last_lon = Double.parseDouble(FastSave.getInstance().getString(Constant.END_LON_1));
try {
Log.d("TAG", "scheduleJob: from next"+last_lat+"..."+last_lon+"///to.."+latitude+"..."+longitude);
GoogleMatrixRequest.calculateKm(context, last_lat, last_lon, latitude, longitude);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Utility.stopScheduleJob(this);
public static void stopScheduleJob(Context context) {
// Toast.makeText(context, "cancel job", Toast.LENGTH_SHORT).show();
if (jobScheduler != null)
{
jobScheduler.cancelAll();
FastSave.getInstance().saveString(Constant.END_LAT_1, "");
FastSave.getInstance().saveString(Constant.END_LON_1, "");
}
}
public class CalculateKmService extends JobService {
#Override
public boolean onStartJob(JobParameters jobParameters) {
// Toast.makeText(this, "schecdule", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onStartJob: working");
Utility.scheduleJob(getBaseContext(), DashboardActivity.startLatitude,DashboardActivity.startLongitude,DashboardActivity.latitude,DashboardActivity.longitude);
return false;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
Utility.stopScheduleJob(getBaseContext());
return false;
}
}
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.sine.provider", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
#Multipart
#POST("add")
Call<AddResponse> doAdd(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("document_type", RequestBody.create(MediaType.parse("text/plain"), "insurance"));
multipart.add(Utility.prepareFilePart(InsurenceActivity.this, "document_file", picturePath));

Related

unable to send data to database, dont know whats wrong with the code

this code was working fine earlier and database have tables made back in 2017, but somehow these are not working any more, unable to create tables in database and retrieve data from it. Android studio throws no error.Stuck with this from last 1 week.
Main activity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private EditText inputName, inputEmail, inputPassword;
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword;
private Button btnSignUp,btnLogout;
//private static final String SITE_URL="http://182.19.41.106/src/okcl/";
private static final String SITE_URL="http://www.wetswd.in/android-data";
private static final String CHECK_URL = SITE_URL+"sign-up.php";
private static final String REGISTER_URL = SITE_URL+"android-process.php";
private static final String UNREGISTER_URL = SITE_URL+"android-process_unregister.php";
private static final String LOGOUT_URL = SITE_URL+"sign-up.php;// logout.php";
private static final String VERSION="1.05";
private static final String pin = "1234";//SN:added for flexibility
private DBHelper mydb ;
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mydb = new DBHelper(this);
//Add from XML Later
//MyReceiver reMyreceive = new MyReceiver();
//IntentFilter filter = new IntentFilter("BROADCAST_ACTION");
//registerReceiver(reMyreceive, filter);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password);
inputName = (EditText) findViewById(R.id.input_name);
inputPassword = (EditText) findViewById(R.id.input_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
Boolean isServiceRunning=isMyServiceRunning(MyService.class);
if(isServiceRunning)
btnSignUp.setBackgroundColor(Color.RED);
else btnSignUp.setBackgroundColor(Color.BLUE);
btnLogout = (Button) findViewById(R.id.btn_logout);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword));
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm(view);
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logOut();
if (!validateName()) {
return;
}
if (!validatePassword()) {
return;
}
String macAdd = getMAC();
String dateTime = getDateTime();
String status = "out_"+inputName.getText().toString().trim();
if (isNetworkAvailable(getApplicationContext())) {
mydb.insertContact(macAdd , dateTime , "0", "0" , status , "N",pin);//inputName.getText().toString().trim(),
logOut(macAdd, inputName.getText().toString().trim(), inputPassword.getText().toString().trim(),pin);
//stopService(); is called inside logout
} else {
mydb.insertContact(macAdd , dateTime , "0", "0" , status.toUpperCase(), "N",pin);//,inputName.getText().toString().trim(),"9999"
btnLogout.setText(R.string.btn_LogOut);// "LOGOUT");
stopService(); //without Checking
Toast.makeText(getApplicationContext(), "LOG Stopped", Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Validating form
*/
private void submitForm(View view) {
if (!validateName()) {
return;
}
if (!validatePassword()) {
return;
}
GPS_Slim gps = new GPS_Slim(MainActivity.this);
//gps.setUsrId(inputName.getText().toString().trim());
//gps.setPin(pin);
if (gps.canGetLocation()) {
double latitude = 20.37;//Near Park;
double longitude = 85.68;//Near Park
double acc=9999.0;//gps.getAccuracy();
String macAdd = getMAC();
String dateTime = getDateTime();
String status = "in_"+inputName.getText().toString().trim();
if(isNetworkAvailable(getApplicationContext())){
mydb.insertContact(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude) , status , "N",pin);//,,String.valueOf(acc)
CheckUser(macAdd ,inputName.getText().toString().trim(),inputPassword.getText().toString().trim(),pin);
}else {
mydb.insertContact(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude) , status.toUpperCase(), "N",pin);//,inputName.getText().toString().trim(),String.valueOf(acc)
Toast.makeText(getApplicationContext(), "Stored Internally", Toast.LENGTH_LONG).show();
btnLogout.setText(R.string.btn_LogOut+" #"+inputName.getText().toString().trim());
startService(); //without Checking//SN:Can I pass Pin here
Toast.makeText(getApplicationContext(), "LOG Started", Toast.LENGTH_LONG).show();
}
} else {
gps.showSettingsAlert();
}
//gps.locationManager.removeUpdates();//SN:Check if used?? GPS object is local here
//gps = null;
}
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
private boolean validatePassword() {
if (inputPassword.getText().toString().trim().isEmpty()) {
inputLayoutPassword.setError(getString(R.string.err_msg_password));
requestFocus(inputPassword);
return false;
} else {
inputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name: validateName(); break;
case R.id.input_password: validatePassword(); break;
}
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private String getMAC(){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
return wInfo.getMacAddress();
}
private String getDateTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private void register(String mac, String dateT, String lat, String lon,String pin,String usr,String ver) {
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("datetime",params[1]);
data.put("lat",params[2]);
data.put("long",params[3]);
data.put("pin",params[4]);//SN:added for Flexibility
data.put("usr",params[5]);//SN:added for Flexibility
data.put("ver",params[6]);//SN:added for Flexibility
return ruc.sendPostRequest(REGISTER_URL,data);
}
}
RegisterUser ru = new RegisterUser();
ru.execute(mac,dateT,lat,lon,pin,usr,ver);
}
private void CheckUser(String mac_id,final String user_id,String password,final String pin) {
class CheckUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Received:"+s,Toast.LENGTH_SHORT).show();
if(s.equalsIgnoreCase("Unauthorised User")){
Toast.makeText(getApplicationContext(),"Login Fail",Toast.LENGTH_LONG).show();
}else{ //Sucessfully Login
double latitude = 20.37;//Near Park;
double longitude = 85.68;//Near Park
String macAdd = getMAC();
String dateTime = getDateTime();
register(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude),pin,user_id,VERSION);
Toast.makeText(getApplicationContext(), "Login Pass", Toast.LENGTH_LONG).show();
startService();
Toast.makeText(getApplicationContext(), "LOG Started", Toast.LENGTH_LONG).show();
btnLogout.setText(btnLogout.getText().toString()+" *"+inputName.getText().toString().trim());
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("userid",params[1]);
data.put("password",params[2]);
data.put("pin",params[3]);
return ruc.sendPostRequest(CHECK_URL,data);
}
}
CheckUser ru = new CheckUser();
ru.execute(mac_id,user_id,password,pin);
}
private void logOut(String mac_id,final String user_id,String password,final String pin) {
class LogOUt extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Received:"+s,Toast.LENGTH_SHORT).show();
if(s.equalsIgnoreCase("Unauthorised User")){
Toast.makeText(getApplicationContext(),"Login Fail",Toast.LENGTH_LONG).show();
}else{ //Sucessfully Login
double latitude = 20.37;//Near Park;20.37 85.68
double longitude = 85.68;//Near Park
String macAdd = getMAC();
String dateTime = getDateTime();
register(macAdd , dateTime ,String.valueOf(latitude), String.valueOf(longitude),pin,user_id,VERSION);
Toast.makeText(getApplicationContext(), "Login Pass", Toast.LENGTH_LONG).show();
//Set Active=0 in android_data for macAdd
stopService();
HashMap<String, String> data = new HashMap<>();
data.put("macid",macAdd);
data.put("pin",pin);//SN:added for Flexibility
String result = ruc.sendPostRequest(UNREGISTER_URL,data);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "LOG Stopped", Toast.LENGTH_LONG).show();//20170821:Sn Testing
btnLogout.setText(R.string.btn_LogOut);//"LOGOUT");
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("userid",params[1]);
data.put("password",params[2]);
data.put("pin",params[3]);
return ruc.sendPostRequest(LOGOUT_URL,data);
}
}
LogOUt ru = new LogOUt();
ru.execute(mac_id,user_id, password,pin);
}
private void doUpdate(String s) {
}
// Method to start the service
public void startService() {Intent i=new Intent(getBaseContext(), MyService.class);
i.putExtra("user",inputName.getText().toString().trim());
i.putExtra("SITE_URL",SITE_URL);
i.putExtra("pin",pin);
i.putExtra("mac",getMAC());
i.putExtra("ver",VERSION);
i.putExtra("REGISTER_URL",REGISTER_URL);
startService(i);
Intent iActivity=new Intent(getBaseContext(), logOut.class);
iActivity.putExtra("user",inputName.getText().toString().trim());
startActivity(iActivity);
}
// Method to start the service
public void stopService() {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.db";
public static final String RECORD_TABLE_NAME = "Record";
public static final String RECORD_COLUMN_ID = "id";
public static final String RECORD_COLUMN_MACID = "macid";
public static final String RECORD_COLUMN_DATETIME = "datetime";
public static final String RECORD_COLUMN_LAT = "lat";
public static final String RECORD_COLUMN_LONG = "long";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Boolean tableExist=isTableExists("Record",false,db);//SN:Not Tested Code Added from https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database
if(!tableExist) {
db.execSQL("create table Record " +
"(id integer primary key, macid text,datetime text,lat text, long text , status text , uploadstatus text, pin text)");
}
//TimeLog Added by SN to KeepTime of Last Update
Boolean timeLogExist=isTableExists("timeLog",false,db);//SN:Not Tested Code Added from https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database
if(!timeLogExist) {
db.execSQL("create table timeLog " + "(id integer primary key, macid text,datetime Long,comment text)");//??SN: Long
//insertTimeLog(0L,"MSG_UPDATE","macid");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS Record");
//db.execSQL("DROP TABLE IF EXISTS timeLog");
onCreate(db);
}
public boolean insertContact (String macid, String datetime, String lat, String longi , String status, String uploadstatus,String pin) { //,String usr,String acc- removed
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//macId,dateTime, String.valueOf(getLatitude()),String.valueOf(getLongitude()),"way","N",pin,usrId,accText
contentValues.put("macid", macid);
contentValues.put("datetime", datetime);
contentValues.put("lat", lat);
contentValues.put("long", longi);
contentValues.put("status", status);
contentValues.put("uploadstatus", uploadstatus);
contentValues.put("pin", pin);
db.insert("Record", null, contentValues);
return true;
}
public boolean updateContactNotUsed (Integer id, String macid, String datetime, String lat, String longi, String status, String uploadstatus) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("macid", macid);
contentValues.put("datetime", datetime);
contentValues.put("lat", lat);
contentValues.put("long", longi);
contentValues.put("status", status);
contentValues.put("uploadstatus", uploadstatus);
db.update("Record", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery( "select * from Record where id="+id+"", null );
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
return (int) DatabaseUtils.queryNumEntries(db, RECORD_TABLE_NAME);
}
public boolean updateTimeLog ( Long datetime, String key) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("datetime", datetime);
db.update("timeLog", contentValues, "comment = ? ", new String[] { key } );
return true;
}
public boolean insertTimeLog ( Long datetime, String key,String macid) { //,String usr,String acc- removed
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("datetime", datetime);
contentValues.put("comment", key);
contentValues.put("macid", macid);
db.insert("timeLog", null, contentValues);
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("Record", "id = ? ", new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from Record", null );
res.moveToFirst();
while(!res.isAfterLast()){
array_list.add(res.getString(res.getColumnIndex(RECORD_TABLE_NAME)));
res.moveToNext();
}
res.close();
return array_list;
}
public boolean isTableExists(String tableName, boolean openDb,SQLiteDatabase mDatabase) {
if(openDb) {
if(mDatabase == null || !mDatabase.isOpen()) {
mDatabase = this.getReadableDatabase();
}
if(!mDatabase.isReadOnly()) {
mDatabase.close();
mDatabase = this.getReadableDatabase();
}
}
Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
}
logcat-https://drive.google.com/file/d/1J1vhdRpP0GOQaRoCycHXWkXi_HiKPxxE/view?usp=sharing
Try upgrading your database version to 2, as your are adding new tables to your database you need to upgrade database version.
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 2);
}

How to do Filter listview in android?

How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.

Fetching education and work details from linked in

I have to fetch LinkedIn details from the loginned user . I am able to get basic basic details through the below code.
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
Now I want to take education and work details.
Educations items = p.getEducations();
System.out.println("items =="+items);
I got values for p.getfirstname(),p.getlastname() but for p.getEducations() , I got null.
I didn't find any solution anywhere. Please help me
Thanks in advance.
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
/*LinkCon Widgets*/
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
/*Intent mycon=new Intent(LinkCon_Main.this, Con_Profile.class);
mycon.putExtra("conid", con_name);
startActivity(mycon);
*/
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}
I have used this api for linkedIn. It helps me to get education, recommendation and career.
http://code.google.com/p/socialauth-android/

my app working fine on online but not working on offline help me

I want to make my application offline .When I am inserting data from url to database it works fine when internet available but my app not show any thing in gridview when no internet available what is wrong in my app please help me why gridview not loading data from database help me
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private boolean isUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DbHelper(this);
dataBase=mHelper.getWritableDatabase();
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID", Category_ID.get(position));
iMenuList.putExtra("Category_name", Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.fff/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
String id = object.getString("category_id");
String name =object.getString("name");
String image_path = object.getString("image_path");
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_MYID,id);
values.put(DbHelper.KEY_FNAME,name);
values.put(DbHelper.KEY_LNAME,image_path );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
displayData();
}
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
//
// Category_ID.clear();
// Category_name.clear();
// Category_image.clear();
if (mCursor.moveToFirst()) {
do {
Category_ID.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
Category_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
Category_image.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
gridview.setAdapter(cla);
mCursor.close();
}
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_MYID="myid";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY
KEY,"+KEY_MYID+" TEXT, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" BLOB)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
a
ndroidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position), true,
true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
check internet Availability before web service call:
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
You have called displayData() only in onPostExecute, so the data is displayed in grid only when you receive data from that URL.
Solution: Call the displayData() once in onCreate function before new TheTask().execute(). So now data will be displayed from the DB if available and then fetch from that URL using HTTPClient. If no internet then the data will still be displayed.
Note: Make sure the cursor size greater than 0 inside displayData(), else display no data text instead of grid view.
happy coding :)
This is quite obvious, You are actually calling you displayData() in postExecute, but in case of no internet, exception will occur you doInBackgroud and null will be passed to postExecute...Exception again in postExecute and your displayData() will not be called.
So first, implement checks for null values to avoid exceptions, and then close try closing you db in catch block.

need help on linkedIn inregration in android

In my android application I'm trying to integrate LinkedIn.I have registered my app with LinkedIn and also have downloaded LinkedIn-j file.I have API key and secret key for application.Now i want to get the auth key for user.I'm not able to understand how to get an Auth key...Please help me..
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
/*LinkCon Widgets*/
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}

Categories

Resources