kaliturin / BlackList

Blacklist Blocker is a free Android application for blocking unwanted calls and SMS
Apache License 2.0
107 stars 37 forks source link

implementing data from server #3

Closed ashudb70 closed 6 years ago

kaliturin commented 7 years ago

Okay then. For adding contact with list of numbers to the Blacklist you can use this:

boolean addContactToBlackList(Context context, String contactName, List<String> stringNumbers) {
        List<DatabaseAccessHelper.ContactNumber> contactNumbers = new LinkedList<>();
        for(String stringNumber : stringNumbers) {
            DatabaseAccessHelper.ContactNumber contactNumber = new DatabaseAccessHelper.ContactNumber(0, stringNumber, 0);
            contactNumbers.add(contactNumber);
        }
        DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context);
        return (db != null && db.addContact(Contact.TYPE_BLACK_LIST, contactName, contactNumbers) >= 0);
    }

After adding, if Blacklist is shown at the moment, you should reload ListView. In ContactsFragment just call reloadItems(null).

ashudb70 commented 7 years ago

where do i add these codes? in my Activity which i created?

kaliturin commented 7 years ago

Yes you can add there.

ashudb70 commented 7 years ago

my code for getting data from server! the issue data from server m fetching is in list view format @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_red);
    listView = (ListView) findViewById(R.id.listView);
    txtMessager = (TextView) findViewById(R.id.tvid);
    txtphoneNo13 = (TextView) findViewById(R.id.tvph);
    data = (Button) findViewById(R.id.data);
    data.setOnClickListener(this);
}

private void sendRequest() {

    StringRequest stringRequest = new StringRequest(JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RedActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String json) {
    ParseJSON pj = new ParseJSON(json);
    pj.parseJSON();
    CustomList cl = new CustomList(this, ParseJSON.ids, ParseJSON.mobile);
    listView.setAdapter(cl);

    //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //  ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();

}

@Override
public void onClick(View v) {

    sendRequest();
    //    databaseAdapter.open();
    //  databaseAdapter.createRecord(t1.getText().toString(),t2.getText().toString());
    //Toast.makeText(getBaseContext(), "insertion done", 5).show();
    //databaseAdapter.close();
}

boolean addContactToBlackList(Context context, String contactName, List<String> stringNumbers) {
    List<DatabaseAccessHelper.ContactNumber> contactNumbers = new LinkedList<>();
    for (String stringNumber : stringNumbers) {
        DatabaseAccessHelper.ContactNumber contactNumber = new DatabaseAccessHelper.ContactNumber(0, stringNumber, 0);
        contactNumbers.add(contactNumber);
    }
    DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context);
    return (db != null && db.addContact(DatabaseAccessHelper.Contact.TYPE_BLACK_LIST, contactName, contactNumbers) >= 0);
}

}

kaliturin commented 7 years ago

Why not just convert fetched numbers into List<> format and then add them?

kaliturin commented 7 years ago

Its OK, keep on talking here. If you have problems with parsing JSON data, just pick up that little tutorial: https://www.tutorialspoint.com/android/android_json_parser.htm

ashudb70 commented 7 years ago

thanks a lot for such guide il attach my code which is` **

public static final String JSON_ARRAY = "MY_JSON"; //public static final String KEY_ID = "id"; public static final String KEY_mobile = "mobile"; //public static final String KEY_EMAIL = "email";

private JSONArray users = null;

private String json;

public ParseJSON(String json){ this.json = json; }

protected void parseJSON(){ JSONObject jsonObject=null; try { JSONArray jsonarray = new JSONArray(json); // jsonObject = new JSONObject(json); //users = jsonObject.getJSONArray(JSON_ARRAY);

    ids = new String[jsonarray.length()];
    mobile = new String[jsonarray.length()];
    //emails = new String[users.length()];

    for(int i=0;i<jsonarray.length();i++){
            JSONObject jo = (JSONObject) jsonarray.get(i);
   // JSONObject jo = users.getJSONObject(i);
   // ids[i] = jo.getString(KEY_ID);
    mobile[i] = jo.getString(KEY_mobile);
  //  emails[i] = jo.getString(KEY_EMAIL);
    }
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }
    }
kaliturin commented 7 years ago

So I just do! Github is pretty good place for talking about coding. After parsing JSON data you have an array of numbers which are stored into ParseJSON.mobile: Pass them into to addContactToBlackList();

private void showJSON(String json) {
    ParseJSON pj = new ParseJSON(json);
    pj.parseJSON();
    // this writes numbers into local DB
    addContactToBlackList(this, "From Server", pj.mobile);

    // after that you can do anything else with this data...
}

boolean addContactToBlackList(Context context, String contactName, String[] stringNumbers) {
    List<DatabaseAccessHelper.ContactNumber> contactNumbers = new LinkedList<>();
    for (String stringNumber : stringNumbers) {
        DatabaseAccessHelper.ContactNumber contactNumber = new DatabaseAccessHelper.ContactNumber(0, stringNumber, 0);
        contactNumbers.add(contactNumber);
    }
    DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context);
    return (db != null && db.addContact(DatabaseAccessHelper.Contact.TYPE_BLACK_LIST, contactName, contactNumbers) >= 0);
}
ashudb70 commented 7 years ago

i didnt get this line "from server" has to be replaced with anything else?

ashudb70 commented 7 years ago

if it gets successful would really love to buy you a coffee/beer! because gonna need your help in next implemntation with U.I

kaliturin commented 7 years ago

Yes you can use any name you wish instead of "From Server". And all numbers you have downloaded will be added into contact named with this name.

kaliturin commented 7 years ago

Another way of adding contacts - without explicit mention of the contact name: addContactToBlackList(this, pj.mobile);

    void addContactToBlackList(Context context, String[] stringNumbers) {
        DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context);
        if(db == null) {
            return;
        }
        for (String stringNumber : stringNumbers) {
            db.addContact(DatabaseAccessHelper.Contact.TYPE_BLACK_LIST, stringNumber, stringNumber);   
        }
    }
ashudb70 commented 7 years ago

thank you soo much bro!

kaliturin commented 7 years ago

For building dialogs I use DialogBuilder. Building "Add a contact" dialog you can find here: com.kaliturin.blacklist.fragments.ContactsFragment#showAddContactsMenuDialog Every item of dialog's menu has callback, in which I open particular activity.

kaliturin commented 7 years ago

If you want to embed you own way of contact adding - I don't think it would be robust and seamless design. But it is your decision. The fragment and layout that show Blacklist/Whitelist: com.kaliturin.blacklist.fragments.ContactsFragment com.kaliturin.blacklist.R.layout#fragment_contacts

ashudb70 commented 7 years ago

if in my activity i want your navigation drawer how do i do that? or back button in action bar as on setting m getting force close! ` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_red);
    listView = (ListView) findViewById(R.id.listView);
    txtMessager = (TextView) findViewById(R.id.tvid);
    txtphoneNo13 = (TextView) findViewById(R.id.tvph);
    data = (Button) findViewById(R.id.data);
    data.setOnClickListener(this);
}

private void sendRequest() {

    StringRequest stringRequest = new StringRequest(JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RedActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String json) {
    ParseJSON pj = new ParseJSON(json);
    pj.parseJSON();
   // addContactToBlackList(this, "From Server", pj.mobile);
    CustomList cl = new CustomList(this, ParseJSON.ids, ParseJSON.mobile);
    listView.setAdapter(cl);
    addContactToBlackList(this, pj.mobile);

    //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //  ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
}

@Override
public void onClick(View v) {

    sendRequest();`
kaliturin commented 7 years ago

I don't know whether you build your activity in my app, or just move pars of code from my app into yours. You should not add drawer to more than one activity in one app. If you want drawer in your own activity - then your activity must be the main and appear at app start. Why don't you add your functionality just into MainActivity of my app. It would be easier than move parts of code from MainActivity into your activity, because code in my activity can have ties with other parts of code and layouts.

ashudb70 commented 7 years ago

thanks for your reply! yes i use your app only i just added activity to your app, i.e the code i pasted above to get data from server if i atleast want back button on top or action bar m getting force close

kaliturin commented 7 years ago

Use Fragment instead of Activity. Open it the same way as I open blackListFragment and others fragments in MainActivity using com.kaliturin.blacklist.activities.MainActivity.FragmentSwitcher. Or you can open your fragment with com.kaliturin.blacklist.activities.CustomFragmentActivity Here is the sample of using it for opening the activity with fragment of SMS-sending (SMSSendFragment):

        Bundle arguments = new Bundle();
        arguments.putString(FragmentArguments.CONTACT_NAME, person);
        arguments.putString(FragmentArguments.CONTACT_NUMBER, number);
        String title = getString(R.string.New_message);
        CustomFragmentActivity.show(this, title, SMSSendFragment.class, arguments);

If you use that way - back button on action bar appears automatically.

When you add fragment into app with File->New->Fragment->Fragment (Blank), opt-out 'Include fragment factory for this methods?' and 'Include interface callback?' and leave 'Create layout XML?' Then fill in fragment's layout with your widgets as you need.

ashudb70 commented 7 years ago

thanks bro this is the first time il be dealing with fragments am neophyte i just hope you be with me to guide if i get stuck at any point, am really sorry if i distrub you! i wil gift you something for sure someday!! your an amazing guy! i need your guidance bro just be there, im sure i can learn and do this!

ashudb70 commented 7 years ago

hey i have created fragment how do i add action bar to it? where do i paste this code? in main activity or in my fragment? Bundle arguments = new Bundle(); arguments.putString(FragmentArguments.CONTACT_NAME, person); arguments.putString(FragmentArguments.CONTACT_NUMBER, number); String title = getString(R.string.New_message); CustomFragmentActivity.show(this, title, SMSSendFragment.class, arguments);

kaliturin commented 7 years ago

In my app this code is placed in MainActivity. Using it I open SMSSendFragment. You may do the same for opening your fragment: CustomFragmentActivity.show(this, "Title of your fragment", YourFragment.class, yourFragmentArguments); Action bar with "back"-button will be added by default.

ashudb70 commented 7 years ago

hi! How do i fix theme bug? i have made a fragament from which on button click i am opening other fragment so theme for fragment remains always dark whenever i try to open fragment from that button click

call.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle arguments = new Bundle(); String title = getString(R.string.Black_list); arguments.putString(TITLE, getString(R.string.Black_list)); CustomFragmentActivity.show(getActivity(), title, ContactsFragment.class, arguments);

        }
    });return view;
kaliturin commented 7 years ago

Why do you think that it is bug? You can't/shouldn't have activities with different themes at the same time. If you have chosen light theme in the Settings - all activities (and fragments) will be light, and all will be dark in other case. Dark theme by default is applied in Manifest for every activity (and fragment inside). Then in Activity.onCreate() you can change it by calling applyCurrentTheme(), where you apply the theme you wish. In my app it depends on Settings.

 private void applyCurrentTheme() {
        if (Settings.getBooleanValue(this, Settings.UI_THEME_LIGHT)) {
            setTheme(R.style.AppTheme_Light);
        } else {
            setTheme(R.style.AppTheme_Dark);
        }
    }
ashudb70 commented 7 years ago

no bro thats not bug thats issue from myside sorry, how do i set light theme always? so that evry fragment is light too

kaliturin commented 7 years ago

If you are in my app - go to the Settings and tap "Light UI theme"

ashudb70 commented 7 years ago

i am aware how do i make it default on installation? imean make the checkbox ticked like in setting block numbers from blacklist is ticked automatically i want the same for light theme how do i do it bro?

kaliturin commented 7 years ago

In com.kaliturin.blacklist.utils.Settings#initDefaults change map.put(UI_THEME_LIGHT, FALSE); to map.put(UI_THEME_LIGHT, TRUE);

ashudb70 commented 7 years ago

May i get Coffee for you? thanks a ton

ashudb70 commented 7 years ago

if i want to launch blacklist fragment in which i can add contact how can i do it? launching from other fragment my code

`call.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Bundle arguments = new Bundle(); //String title = getString(R.string.Black_list); //arguments.putString(TITLE, getString(R.string.Black_list)); //CustomFragmentActivity.show(getContext(), title, AddContactsFragment.class, arguments);

           showAddContactsActivity(Permissions.WRITE_EXTERNAL_STORAGE,
                    ContactSourceType.FROM_BLACK_LIST,
                    R.string.Black_list);

        }
    });return view;

`

ashudb70 commented 7 years ago

bro i have submission today please guide me

kaliturin commented 7 years ago

I didn't understand your question. If you want to launch activity with fragment of adding contacts, then yes this method is right: com.kaliturin.blacklist.fragments.ContactsFragment#showAddContactsActivity

ashudb70 commented 7 years ago

no no i want to launch blacklist fragment from my home fragment on button click

ashudb70 commented 7 years ago

i have home fragment in that i have button on clicking the button i want to launch blacklist fragment in which i can add contact to blacklist or the other way round method is right: com.kaliturin.blacklist.fragments.ContactsFragment#showAddContactsActivity m getting this hw do i move the added list to blacklist ?

kaliturin commented 7 years ago

You should clarify your intentions. As you can see from source com.kaliturin.blacklist.fragments.ContactsFragment#showAddContactsActivity opens activity with fragment for adding contact from predefined sources or manually. Sources are: ContactSourceType.FROM_CONTACTS, ContactSourceType.FROM_CALLS_LOG, ContactSourceType.FROM_SMS_LIST, ContactSourceType.FROM_BLACK_LIST, ContactSourceType.FROM_WHITE_LIST and null (means manually adding). So where from do you want to add contacts? (Which source?)

ashudb70 commented 7 years ago

after adding how do i move it to blacklist like you helped me in doing from server am executing this code on button click m executing this Bundle arguments = new Bundle(); String title = getString(R.string.Black_list); arguments.putString(TITLE, getString(R.string.Black_list)); CustomFragmentActivity.show(getActivity(), title, ContactsFragment.class, arguments);

i can add contact to that list but how do i copy the added contact from there the list which am getting on executing the code i pasted above to blacklist

kaliturin commented 7 years ago

As I understand you want to add contacts from the new source - "server". So why don't you just add such source to com.kaliturin.blacklist.utils.ContactsAccessHelper.ContactSourceType and implement adding the same way as is implemented for all other sources in com.kaliturin.blacklist.utils.ContactsAccessHelper#getContacts(android.content.Context, com.kaliturin.blacklist.utils.ContactsAccessHelper.ContactSourceType, java.lang.String)

kaliturin commented 7 years ago

In com.kaliturin.blacklist.utils.ContactsAccessHelper

// Types of the contact sources
    public enum ContactSourceType {
       ...
       FROM_SERVER
    }
public Cursor getContacts(Context context, ContactSourceType sourceType, @Nullable String filter) {
...
// return contacts
switch (sourceType) {
...
case FROM_SERVER:
       ServerAccessHelper helper = new ServerAccessHelper();
       return helper.getContacts()
}
...
}
// This class you should implement
class ServerAccessHelper {
...
}
ashudb70 commented 7 years ago

hi bro may i ask u a question if i want traceroute in android how can i implement ? imean am getting traceroute on wifi network but not over cellular do u know command for getting traceroute?

ashudb70 commented 7 years ago

String format = "ping -c 1 -t %d "; command = String.format(format, ttl);

        Log.d(TraceActivity.tag, "Will launch : " + command + url);

        long startTime = System.nanoTime();
        elapsedTime = 0;
        // timeout task
        new TimeOutAsyncTask(this, ttl).execute();
        // Launch command
        p = Runtime.getRuntime().exec(command + url);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        // Construct the response from ping
        String s;
        String res = "";
        while ((s = stdInput.readLine()) != null) {
            res += s + "\n";
            if (s.contains(FROM_PING) || s.contains(SMALL_FROM_PING)) {
                // We store the elapsedTime when the line from ping comes
                elapsedTime = (System.nanoTime() - startTime) / 1000000.0f;
            }
        }

        p.destroy();

        if (res.equals("")) {
            throw new IllegalArgumentException();
        }
kaliturin commented 7 years ago

Sorry, but I can't give you any advice on this

ashudb70 commented 7 years ago

Hi have added image button to you sms conversation cursor adapter in view holder How do launch move to black list from its view.onclicklistner

ashudb70 commented 7 years ago

i have added textview to cursor adapter i want to implement onclicklistener for it so that it can launch dialog ViewHolder(View rowView, TextView addressTextView, TextView snippetTextView, TextView dateTextView, TextView iconview, TextView unreadTextView) { this.model = null; this.rowView = rowView; this.addressTextView = addressTextView; this.snippetTextView = snippetTextView; this.dateTextView = dateTextView; this.iconview =iconview; this.unreadTextView = unreadTextView;

kaliturin commented 7 years ago

Adding photo - this is exactly what I wanna do in the one of the next release. Just wait and see. ;-> Now I have no idea how to do it better. A little bit busy with other things. You are free to improvise.

ashudb70 commented 7 years ago

bro if i wish to add colour to list view example i long pressed on message to add to blacklist n now i wana change colour to red so can u guide in smsconversationlist fragment how do i do it

private void loadListViewItems(boolean markSeen, boolean showProgress) { int listPosition = listView.getFirstVisiblePosition(); loadListViewItems(listPosition, markSeen, showProgress); }

    // Loads SMS conversations to the list view
    private void loadListViewItems(int listPosition, boolean markSeen, boolean showProgress) {
        if (!isAdded()) {
            return;
        }
        int loaderId = 0;
        ConversationsLoaderCallbacks callbacks =
                new ConversationsLoaderCallbacks(getContext(), listView,
                        listPosition, cursorAdapter, markSeen, showProgress);

        LoaderManager manager = getLoaderManager();
        Loader<?> loader = manager.getLoader(loaderId);
        if (loader == null) {
            // init and run the items loader
            manager.initLoader(loaderId, null, callbacks);
        } else {
            // restart loader
            manager.restartLoader(loaderId, null, callbacks);
        }
    }
kaliturin commented 7 years ago

Here you can get row of list on long click: com.kaliturin.blacklist.fragments.SMSConversationsListFragment.OnRowLongClickListener#onLongClick Inside you can call row.setBackgroundColor(yourColor) or row.setBackdround(yourDrawable) as you wish.

ashudb70 commented 7 years ago

its working but colour doesnt stay persisitant the moment i go back and come again to activity it disappears

kaliturin commented 7 years ago

It is because here: layout/row_sms_conversations_list.xml:5 there is android:background="?selector_control" where selector_control is reference to drawable/selector_control_light.xml (for light theme) which defines color of view depending on view state: state_pressed and/or state_checked. For example <item android:drawable="@color/pressed_d" android:state_pressed="true" /> means that if view is pressed it gets color @color/pressed_d and so on. Here are more details: https://developer.android.com/guide/topics/resources/drawable-resource.html

ashudb70 commented 7 years ago

so how do i remove it? for row i want that when your dialog menu open i press on select add to blacklist in that case the colour of SMS conversaton list row changes to red but when i come back from other fragment it is restored , so far i can change colour of like pressed state and all!

ashudb70 commented 7 years ago

if state is pressed it shud be permanent in that case what value do i change? in your selector xml version="1.0" encoding="utf-8" selector xmlns:android="http://schemas.android.com/apk/res/android" item android:drawable="@color/pressed" android:state_pressed="true" item android:drawable="@android:color/transparent" android:state_checked="false" android:state_pressed="false" item android:drawable="@color/checked" android:state_checked="true" android:state_pressed="false" selector